DomainDig/ContentView.swift

9384a668bf36f23f71e25d05b490d1040d308845
domain-dig/DomainDig/ContentView.swift history · blame · raw

2051 lines · 87482 bytes

   1import MapKit
   2import SwiftUI
   3
   4enum LookupInputMode: String, CaseIterable, Identifiable {
   5    case single
   6    case bulk
   7
   8    var id: String { rawValue }
   9}
  10
  11enum ResultSection: String, Hashable {
  12    case domain
  13    case ownership
  14    case dns
  15    case web
  16    case email
  17    case network
  18    case subdomains
  19}
  20
  21private struct WorkflowNavigationTarget: Hashable {
  22    let workflowID: UUID
  23}
  24
  25struct ContentView: View {
  26    @Environment(\.appDensity) private var appDensity
  27    @State private var viewModel = DomainViewModel()
  28    @State private var navigationPath = NavigationPath()
  29    @FocusState private var domainFieldFocused: Bool
  30    @State private var customPortInput = ""
  31    @State private var customPortsExpanded = false
  32    @State private var trackingNoteDraft = ""
  33    @State private var editingTrackedDomain: TrackedDomain?
  34    @State private var showTrackLimitAlert = false
  35    @State private var inputMode: LookupInputMode = .single
  36    @State private var collapsedSections: Set<ResultSection> = [.network]
  37    @State private var showingCurrentDomainWorkflowSheet = false
  38    @State private var showingBatchWorkflowSheet = false
  39
  40    var body: some View {
  41        NavigationStack(path: $navigationPath) {
  42            ScrollView(.vertical) {
  43                VStack(spacing: 0) {
  44                    inputSection
  45                    if !viewModel.batchResults.isEmpty || viewModel.batchLookupRunning {
  46                        batchSection
  47                            .padding(.top, appDensity.metrics.cardSpacing)
  48                    }
  49                    if viewModel.hasRun {
  50                        actionButtons
  51                        if !viewModel.resultsLoaded {
  52                            LookupProgressOverviewView(steps: viewModel.activeLoadingLabels)
  53                                .padding(.top, appDensity.metrics.cardSpacing)
  54                        } else if let statusMessage = resultStatusMessage {
  55                            LookupStatusBannerView(message: statusMessage, resultSource: viewModel.currentResultSource)
  56                                .padding(.top, appDensity.metrics.cardSpacing)
  57                        }
  58                        if viewModel.resultsLoaded {
  59                            SummaryView(fields: viewModel.summaryFields)
  60                                .padding(.top, appDensity.metrics.cardSpacing)
  61                            if let changeSummary = viewModel.currentChangeSummary {
  62                                DomainChangeSummaryView(summary: changeSummary)
  63                                    .padding(.top, appDensity.metrics.cardSpacing)
  64                            }
  65                        }
  66                        DomainSectionView(
  67                            isCollapsed: sectionCollapsedBinding(.domain),
  68                            rows: viewModel.domainRows,
  69                            suggestions: viewModel.suggestionRows,
  70                            showSuggestions: viewModel.availabilityResult?.status == .registered || viewModel.suggestionsLoading,
  71                            availabilityLoading: viewModel.availabilityLoading,
  72                            suggestionsLoading: viewModel.suggestionsLoading,
  73                            provenance: viewModel.currentSnapshot.provenanceBySection[.availability],
  74                            confidence: viewModel.currentSnapshot.availabilityConfidence,
  75                            snapshotNote: viewModel.currentSnapshot.note,
  76                            trackedDomain: viewModel.currentTrackedDomain,
  77                            workflows: viewModel.currentDomainWorkflows,
  78                            trackingLimitMessage: viewModel.trackingLimitMessage,
  79                            onTrack: {
  80                                if !viewModel.trackCurrentDomain() {
  81                                    showTrackLimitAlert = true
  82                                }
  83                            },
  84                            onTogglePinned: {
  85                                guard let trackedDomain = viewModel.currentTrackedDomain else { return }
  86                                viewModel.togglePinned(for: trackedDomain)
  87                            },
  88                            onEditNote: {
  89                                guard let trackedDomain = viewModel.currentTrackedDomain else { return }
  90                                trackingNoteDraft = trackedDomain.note ?? ""
  91                                editingTrackedDomain = trackedDomain
  92                            },
  93                            onAddToWorkflow: {
  94                                showingCurrentDomainWorkflowSheet = true
  95                            },
  96                            onOpenWorkflow: { workflow in
  97                                navigationPath.append(WorkflowNavigationTarget(workflowID: workflow.id))
  98                            },
  99                            onRunWorkflow: { workflow in
 100                                viewModel.rerunCurrentDomain(in: workflow)
 101                            }
 102                        )
 103                            .padding(.top, appDensity.metrics.sectionSpacing)
 104                        OwnershipSectionView(
 105                            isCollapsed: sectionCollapsedBinding(.ownership),
 106                            rows: viewModel.ownershipRows,
 107                            loading: viewModel.ownershipLoading,
 108                            error: viewModel.ownershipError,
 109                            provenance: viewModel.currentSnapshot.provenanceBySection[.ownership],
 110                            confidence: viewModel.currentSnapshot.ownershipConfidence,
 111                            showsHistoryPlaceholder: !DataAccessService.hasAccess(to: .ownershipHistory)
 112                        )
 113                        .padding(.top, appDensity.metrics.sectionSpacing)
 114                        SubdomainsSectionView(
 115                            isCollapsed: sectionCollapsedBinding(.subdomains),
 116                            rows: viewModel.subdomainRows,
 117                            loading: viewModel.subdomainsLoading,
 118                            error: viewModel.subdomainsError,
 119                            provenance: viewModel.currentSnapshot.provenanceBySection[.subdomains],
 120                            confidence: viewModel.currentSnapshot.subdomainConfidence,
 121                            showsExtendedPlaceholder: !DataAccessService.hasAccess(to: .extendedSubdomains)
 122                        )
 123                        .padding(.top, appDensity.metrics.sectionSpacing)
 124                        if !viewModel.currentDiffSections.isEmpty {
 125                            DomainDiffView(
 126                                title: "Latest Changes",
 127                                sections: viewModel.currentDiffSections,
 128                                contextNote: viewModel.currentChangeSummary?.contextNote,
 129                                showsUnchanged: false
 130                            )
 131                            .padding(.top, appDensity.metrics.sectionSpacing)
 132                        }
 133                        DNSSectionView(
 134                            isCollapsed: sectionCollapsedBinding(.dns),
 135                            dnssecLabel: viewModel.dnssecLabel,
 136                            sections: viewModel.dnsRows,
 137                            ptrMessage: viewModel.ptrMessage,
 138                            loading: viewModel.dnsLoading || viewModel.ptrLoading,
 139                            dnsProvenance: viewModel.currentSnapshot.provenanceBySection[.dns],
 140                            ptrProvenance: viewModel.currentSnapshot.provenanceBySection[.ptr],
 141                            sectionError: viewModel.dnsError
 142                        )
 143                        .padding(.top, appDensity.metrics.sectionSpacing)
 144                        WebSectionView(
 145                            isCollapsed: sectionCollapsedBinding(.web),
 146                            certificateRows: viewModel.webCertificateRows,
 147                            sslInfo: viewModel.sslInfo,
 148                            sslLoading: viewModel.sslLoading || viewModel.hstsLoading,
 149                            sslError: viewModel.sslError,
 150                            tlsProvenance: viewModel.currentSnapshot.provenanceBySection[.ssl],
 151                            responseRows: viewModel.webResponseRows,
 152                            headers: viewModel.httpHeaders,
 153                            headersLoading: viewModel.httpHeadersLoading,
 154                            headersError: viewModel.httpHeadersError,
 155                            httpProvenance: viewModel.currentSnapshot.provenanceBySection[.httpHeaders],
 156                            redirects: viewModel.redirectRows,
 157                            redirectLoading: viewModel.redirectChainLoading,
 158                            redirectError: viewModel.redirectChainError,
 159                            redirectProvenance: viewModel.currentSnapshot.provenanceBySection[.redirectChain],
 160                            finalURL: viewModel.currentSnapshot.redirectChain.last?.url
 161                        )
 162                        .padding(.top, appDensity.metrics.sectionSpacing)
 163                        EmailSectionView(
 164                            isCollapsed: sectionCollapsedBinding(.email),
 165                            rows: viewModel.emailRows,
 166                            loading: viewModel.emailSecurityLoading,
 167                            provenance: viewModel.currentSnapshot.provenanceBySection[.emailSecurity],
 168                            confidence: viewModel.currentSnapshot.emailSecurityConfidence,
 169                            error: viewModel.emailSecurityError
 170                        )
 171                        .padding(.top, appDensity.metrics.sectionSpacing)
 172                        NetworkSectionView(
 173                            isCollapsed: sectionCollapsedBinding(.network),
 174                            reachabilityRows: viewModel.reachabilityRows,
 175                            reachabilityLoading: viewModel.reachabilityLoading,
 176                            reachabilityError: viewModel.reachabilityError,
 177                            reachabilityProvenance: viewModel.currentSnapshot.provenanceBySection[.reachability],
 178                            locationRows: viewModel.locationRows,
 179                            geolocation: viewModel.ipGeolocation,
 180                            geolocationLoading: viewModel.ipGeolocationLoading,
 181                            geolocationError: viewModel.ipGeolocationError,
 182                            geolocationProvenance: viewModel.currentSnapshot.provenanceBySection[.ipGeolocation],
 183                            geolocationConfidence: viewModel.currentSnapshot.geolocationConfidence,
 184                            standardPortRows: viewModel.standardPortRows,
 185                            customPortRows: viewModel.customPortRows,
 186                            portScanLoading: viewModel.portScanLoading,
 187                            portScanError: viewModel.portScanError,
 188                            portScanProvenance: viewModel.currentSnapshot.provenanceBySection[.portScan],
 189                            customPortScanLoading: viewModel.customPortScanLoading,
 190                            customPortScanError: viewModel.customPortScanError,
 191                            isCloudflareProxied: viewModel.isCloudflareProxied,
 192                            customPortsExpanded: $customPortsExpanded,
 193                            customPortInput: $customPortInput,
 194                            onScanCustomPorts: runCustomPortScan
 195                        )
 196                        .padding(.top, appDensity.metrics.sectionSpacing)
 197                    } else if !viewModel.recentSearches.isEmpty {
 198                        recentSearchesSection
 199                    }
 200                }
 201                .padding(.horizontal)
 202                .padding(.bottom, 32)
 203            }
 204            .background(
 205                LinearGradient(
 206                    colors: [Color.black, Color(.systemGray6).opacity(0.12)],
 207                    startPoint: .top,
 208                    endPoint: .bottom
 209                )
 210            )
 211            .navigationTitle("DomainDig")
 212            .toolbarColorScheme(.dark, for: .navigationBar)
 213            .preferredColorScheme(.dark)
 214            .toolbar {
 215                ToolbarItemGroup(placement: .topBarTrailing) {
 216                    if viewModel.hasRun {
 217                        Button {
 218                            viewModel.reset()
 219                        } label: {
 220                            Image(systemName: "xmark.circle")
 221                                .foregroundStyle(.secondary)
 222                        }
 223                    }
 224                    NavigationLink {
 225                        WatchlistView(viewModel: viewModel)
 226                    } label: {
 227                        Image(systemName: "eye")
 228                            .foregroundStyle(.secondary)
 229                    }
 230                    Menu {
 231                        NavigationLink {
 232                            HistoryView(viewModel: viewModel)
 233                        } label: {
 234                            Label("History", systemImage: "clock.arrow.trianglehead.counterclockwise.rotate.90")
 235                        }
 236
 237                        NavigationLink {
 238                            SavedDomainsView(viewModel: viewModel)
 239                        } label: {
 240                            Label("Saved Domains", systemImage: "bookmark")
 241                        }
 242
 243                        NavigationLink {
 244                            WorkflowsView(viewModel: viewModel)
 245                        } label: {
 246                            Label("Workflows", systemImage: "square.stack.3d.down.right")
 247                        }
 248
 249                        NavigationLink {
 250                            SettingsView(viewModel: viewModel)
 251                        } label: {
 252                            Label("Settings", systemImage: "gearshape")
 253                        }
 254                    } label: {
 255                        Image(systemName: "ellipsis.circle")
 256                            .foregroundStyle(.secondary)
 257                    }
 258                }
 259            }
 260            .navigationDestination(for: WorkflowNavigationTarget.self) { target in
 261                WorkflowDetailView(viewModel: viewModel, workflowID: target.workflowID)
 262            }
 263        }
 264        .onAppear {
 265            domainFieldFocused = true
 266        }
 267        .onChange(of: viewModel.searchedDomain) { _, _ in
 268            collapsedSections = defaultCollapsedSections
 269        }
 270        .onChange(of: viewModel.rerunNavigationToken) { _, _ in
 271            navigationPath = NavigationPath()
 272            domainFieldFocused = false
 273        }
 274        .alert("Tracking limit reached", isPresented: $showTrackLimitAlert) {
 275            Button("OK", role: .cancel) {}
 276        } message: {
 277            Text("Free version supports up to 3 tracked domains. More tracked domains will be available in a future Pro upgrade.")
 278        }
 279        .sheet(item: $editingTrackedDomain) { trackedDomain in
 280            NavigationStack {
 281                Form {
 282                    Section("Tracking Note") {
 283                        TextField("Optional note", text: $trackingNoteDraft, axis: .vertical)
 284                            .lineLimit(3...6)
 285                            .textInputAutocapitalization(.never)
 286                            .autocorrectionDisabled()
 287                    }
 288                }
 289                .navigationTitle(trackedDomain.domain)
 290                .toolbar {
 291                    ToolbarItem(placement: .cancellationAction) {
 292                        Button("Cancel") {
 293                            editingTrackedDomain = nil
 294                        }
 295                    }
 296                    ToolbarItem(placement: .confirmationAction) {
 297                        Button("Save") {
 298                            viewModel.updateNote(trackingNoteDraft, for: trackedDomain)
 299                            editingTrackedDomain = nil
 300                        }
 301                    }
 302                }
 303            }
 304        }
 305        .sheet(isPresented: $showingCurrentDomainWorkflowSheet) {
 306            WorkflowBulkAddSheet(
 307                viewModel: viewModel,
 308                title: "Add Domain to Workflow",
 309                availableDomains: [viewModel.searchedDomain]
 310            )
 311        }
 312        .sheet(isPresented: $showingBatchWorkflowSheet) {
 313            WorkflowBulkAddSheet(
 314                viewModel: viewModel,
 315                title: "Add Batch Domains",
 316                availableDomains: viewModel.batchResults.map(\.domain)
 317            )
 318        }
 319    }
 320
 321    private var inputSection: some View {
 322        VStack(spacing: appDensity.metrics.cardSpacing + 2) {
 323            Picker("Mode", selection: $inputMode) {
 324                Text("Single").tag(LookupInputMode.single)
 325                Text("Bulk").tag(LookupInputMode.bulk)
 326            }
 327            .pickerStyle(.segmented)
 328
 329            if inputMode == .single {
 330                TextField("e.g. cleberg.net", text: $viewModel.domain)
 331                    .font(appDensity.font(.title3, design: .monospaced))
 332                    .textInputAutocapitalization(.never)
 333                    .autocorrectionDisabled()
 334                    .keyboardType(.URL)
 335                    .padding(.horizontal, 12)
 336                    .padding(.vertical, appDensity.metrics.controlVerticalPadding)
 337                    .background(Color(.systemGray6))
 338                    .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
 339                    .focused($domainFieldFocused)
 340                    .onSubmit { viewModel.run() }
 341
 342                Button {
 343                    domainFieldFocused = false
 344                    viewModel.run()
 345                } label: {
 346                    Text("Run")
 347                        .font(appDensity.font(.headline, design: .default, weight: .semibold))
 348                        .frame(maxWidth: .infinity)
 349                        .frame(minHeight: appDensity.metrics.controlMinHeight)
 350                }
 351                .buttonStyle(.borderedProminent)
 352                .disabled(viewModel.trimmedDomain.isEmpty)
 353            } else {
 354                VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
 355                    Text("Paste domains separated by new lines or commas.")
 356                        .font(appDensity.font(.caption))
 357                        .foregroundStyle(.secondary)
 358
 359                    TextField(
 360                        "example.com\napple.com, openai.com",
 361                        text: $viewModel.bulkInput,
 362                        axis: .vertical
 363                    )
 364                    .font(appDensity.font(.body))
 365                    .textInputAutocapitalization(.never)
 366                    .autocorrectionDisabled()
 367                    .keyboardType(.URL)
 368                    .lineLimit(4...10)
 369                    .padding(.horizontal, 12)
 370                    .padding(.vertical, appDensity.metrics.controlVerticalPadding)
 371                    .background(Color(.systemGray6))
 372                    .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
 373
 374                    Button {
 375                        domainFieldFocused = false
 376                        viewModel.runBulkLookup()
 377                    } label: {
 378                        Text(viewModel.batchLookupRunning ? "Running Batch…" : "Run Batch")
 379                            .font(appDensity.font(.headline, design: .default, weight: .semibold))
 380                            .frame(maxWidth: .infinity)
 381                            .frame(minHeight: appDensity.metrics.controlMinHeight)
 382                    }
 383                    .buttonStyle(.borderedProminent)
 384                    .disabled(viewModel.bulkInput.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || viewModel.batchLookupRunning)
 385                }
 386            }
 387        }
 388        .padding(.vertical, appDensity.metrics.sectionSpacing)
 389    }
 390
 391    private var actionButtons: some View {
 392        HStack {
 393            Spacer()
 394            if viewModel.resultsLoaded {
 395                Menu {
 396                    if !viewModel.isCurrentDomainTracked {
 397                        Button("Track this domain") {
 398                            if !viewModel.trackCurrentDomain() {
 399                                showTrackLimitAlert = true
 400                            }
 401                        }
 402                    }
 403                    Button("Add to workflow") {
 404                        showingCurrentDomainWorkflowSheet = true
 405                    }
 406                    Button("Copy report JSON") {
 407                        guard let json = viewModel.exportJSONString() else { return }
 408                        AppClipboard.copy(json)
 409                        AppHaptics.copy()
 410                    }
 411                    Button("Export report") {
 412                        shareSingleResults(format: .json)
 413                    }
 414                } label: {
 415                    Image(systemName: "bolt.circle")
 416                        .font(appDensity.font(.body, design: .default))
 417                        .foregroundStyle(.secondary)
 418                }
 419                Button {
 420                    viewModel.toggleSavedDomain()
 421                } label: {
 422                    Image(systemName: viewModel.isCurrentDomainSaved ? "bookmark.fill" : "bookmark")
 423                        .font(appDensity.font(.body, design: .default))
 424                        .foregroundStyle(viewModel.isCurrentDomainSaved ? .yellow : .secondary)
 425                }
 426                Menu {
 427                    Button("Export TXT") {
 428                        shareSingleResults(format: .text)
 429                    }
 430                    Button("Export CSV") {
 431                        shareSingleResults(format: .csv)
 432                    }
 433                    Button("Export JSON") {
 434                        shareSingleResults(format: .json)
 435                    }
 436                } label: {
 437                    Image(systemName: "square.and.arrow.up")
 438                        .font(appDensity.font(.body, design: .default))
 439                        .foregroundStyle(.secondary)
 440                }
 441            }
 442        }
 443    }
 444
 445    private var batchSection: some View {
 446        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
 447            HStack {
 448                Spacer()
 449                if viewModel.batchLookupRunning {
 450                    Button("Cancel") {
 451                        viewModel.cancelBatchLookup()
 452                    }
 453                    .buttonStyle(.bordered)
 454                    .font(appDensity.font(.caption))
 455                }
 456                if !viewModel.currentBatchResultEntries.isEmpty {
 457                    Menu {
 458                        Button("Add to Workflow") {
 459                            showingBatchWorkflowSheet = true
 460                        }
 461                        Divider()
 462                        Button("Export Batch TXT") {
 463                            shareBatchResults(format: .text)
 464                        }
 465                        Button("Export Batch CSV") {
 466                            shareBatchResults(format: .csv)
 467                        }
 468                        Button("Export Batch JSON") {
 469                            shareBatchResults(format: .json)
 470                        }
 471                    } label: {
 472                        Label("Export", systemImage: "square.and.arrow.up")
 473                            .font(appDensity.font(.caption))
 474                    }
 475                    .buttonStyle(.bordered)
 476                }
 477            }
 478
 479            BatchResultsView(
 480                viewModel: viewModel,
 481                title: viewModel.batchLookupSource == .watchlistRefresh ? "Tracked Domain Refresh" : "Batch Results"
 482            )
 483        }
 484    }
 485
 486    private var recentSearchesSection: some View {
 487        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
 488            HStack {
 489                Text("RECENT")
 490                    .font(appDensity.font(.caption2))
 491                    .foregroundStyle(.secondary)
 492                Spacer()
 493                Button("Clear") {
 494                    viewModel.clearRecentSearches()
 495                }
 496                .font(appDensity.font(.caption2))
 497                .foregroundStyle(.secondary)
 498            }
 499
 500            ForEach(viewModel.recentSearches, id: \.self) { domain in
 501                Button {
 502                    viewModel.domain = domain
 503                    domainFieldFocused = false
 504                    viewModel.run()
 505                } label: {
 506                    Text(domain)
 507                        .font(appDensity.font(.callout))
 508                        .foregroundStyle(.primary)
 509                        .frame(maxWidth: .infinity, alignment: .leading)
 510                        .padding(.vertical, 8)
 511                        .padding(.horizontal, 10)
 512                        .background(Color(.systemGray6).opacity(0.5))
 513                        .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
 514                }
 515            }
 516        }
 517        .padding(.top, appDensity.metrics.cardSpacing)
 518    }
 519
 520    private func runCustomPortScan() {
 521        let ports = parsedCustomPorts(from: customPortInput)
 522        Task {
 523            await viewModel.runCustomPortScan(ports: ports)
 524        }
 525    }
 526
 527    private func parsedCustomPorts(from input: String) -> [UInt16] {
 528        let parts = input.split(separator: ",", omittingEmptySubsequences: true)
 529        var seen = Set<UInt16>()
 530        var ports: [UInt16] = []
 531
 532        for part in parts {
 533            let trimmed = part.trimmingCharacters(in: .whitespacesAndNewlines)
 534            guard let value = UInt16(trimmed), seen.insert(value).inserted else {
 535                continue
 536            }
 537            ports.append(value)
 538            if ports.count == 20 {
 539                break
 540            }
 541        }
 542
 543        return ports
 544    }
 545
 546    private func shareSingleResults(format: DomainExportFormat) {
 547        let (filename, data) = exportPayload(
 548            prefix: "domaindig_single",
 549            format: format,
 550            text: viewModel.exportText(),
 551            csv: viewModel.exportCSV(),
 552            json: viewModel.exportJSONData()
 553        )
 554        ExportPresenter.share(filename: filename, data: data)
 555    }
 556
 557    private func shareBatchResults(format: DomainExportFormat) {
 558        let (filename, data) = exportPayload(
 559            prefix: "domaindig_batch",
 560            format: format,
 561            text: viewModel.exportBatchText(),
 562            csv: viewModel.exportBatchCSV(),
 563            json: viewModel.exportBatchJSONData()
 564        )
 565        ExportPresenter.share(filename: filename, data: data)
 566    }
 567
 568    private func exportPayload(
 569        prefix: String,
 570        format: DomainExportFormat,
 571        text: String,
 572        csv: String,
 573        json: Data?
 574    ) -> (String, Data) {
 575        let formatter = DateFormatter()
 576        formatter.dateFormat = "yyyyMMdd_HHmmss"
 577        let timestamp = formatter.string(from: Date())
 578        let filename = "\(timestamp)_\(prefix).\(format.fileExtension)"
 579        let data: Data
 580
 581        switch format {
 582        case .text:
 583            data = Data(text.utf8)
 584        case .csv:
 585            data = Data(csv.utf8)
 586        case .json:
 587            data = json ?? Data("[]".utf8)
 588        }
 589
 590        return (filename, data)
 591    }
 592
 593    private var defaultCollapsedSections: Set<ResultSection> {
 594        []
 595    }
 596
 597    private var currentPrimaryIP: String? {
 598        viewModel.currentSnapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
 599    }
 600
 601    private var resultStatusMessage: String? {
 602        if let currentStatusMessage = viewModel.currentStatusMessage {
 603            return currentStatusMessage
 604        }
 605
 606        if viewModel.currentResultSource != .live {
 607            return viewModel.currentResultSource.label
 608        }
 609
 610        return nil
 611    }
 612
 613    private func sectionCollapsedBinding(_ section: ResultSection) -> Binding<Bool> {
 614        Binding(
 615            get: { collapsedSections.contains(section) },
 616            set: { isCollapsed in
 617                if isCollapsed {
 618                    collapsedSections.insert(section)
 619                } else {
 620                    collapsedSections.remove(section)
 621                }
 622            }
 623        )
 624    }
 625}
 626
 627struct SummaryView: View {
 628    @Environment(\.appDensity) private var appDensity
 629    let fields: [SummaryFieldViewData]
 630
 631    var body: some View {
 632        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
 633            SectionTitleView(title: "Summary")
 634            LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: appDensity.metrics.cardSpacing) {
 635                ForEach(fields) { field in
 636                    VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing) {
 637                        Text(field.label)
 638                            .font(appDensity.font(.caption2))
 639                            .foregroundStyle(.secondary)
 640                        Text(field.value)
 641                            .font(appDensity.font(.caption))
 642                            .foregroundStyle(ResultColors.color(for: field.tone))
 643                            .lineLimit(2)
 644                            .textSelection(.enabled)
 645                    }
 646                    .frame(minHeight: appDensity.metrics.rowMinHeight + 12, alignment: .topLeading)
 647                    .frame(maxWidth: .infinity, alignment: .leading)
 648                    .padding(appDensity.metrics.cardPadding)
 649                    .background(Color(.systemGray6).opacity(0.5))
 650                    .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
 651                }
 652            }
 653        }
 654    }
 655}
 656
 657struct StickyLookupSummaryView: View {
 658    @Environment(\.appDensity) private var appDensity
 659
 660    let domain: String
 661    let availability: DomainAvailabilityStatus?
 662    let primaryIP: String?
 663    let sslInfo: SSLCertificateInfo?
 664    let sslError: String?
 665    let emailSecurity: EmailSecurityResult?
 666    let emailError: String?
 667    let changeSummary: DomainChangeSummary?
 668
 669    var body: some View {
 670        CardView(allowsHorizontalScroll: false) {
 671            VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
 672                HStack(alignment: .center, spacing: 10) {
 673                    Text(domain)
 674                        .font(appDensity.font(.headline, weight: .semibold))
 675                        .foregroundStyle(.primary)
 676                        .lineLimit(1)
 677                    Spacer(minLength: 6)
 678                    AppCopyButton(value: domain, label: "Copy domain")
 679                }
 680
 681                ScrollView(.horizontal, showsIndicators: false) {
 682                    HStack(spacing: 8) {
 683                        AppStatusBadgeView(model: AppStatusFactory.availability(availability))
 684                        AppStatusBadgeView(model: AppStatusFactory.tls(sslInfo: sslInfo, error: sslError))
 685                        AppStatusBadgeView(model: AppStatusFactory.email(emailSecurity, error: emailError))
 686                        AppStatusBadgeView(model: AppStatusFactory.change(changeSummary))
 687                    }
 688                }
 689
 690                if let primaryIP {
 691                    HStack(spacing: 8) {
 692                        Label(primaryIP, systemImage: "network")
 693                            .font(appDensity.font(.caption))
 694                            .foregroundStyle(.secondary)
 695                        Spacer(minLength: 6)
 696                        AppCopyButton(value: primaryIP, label: "Copy IP")
 697                    }
 698                }
 699            }
 700        }
 701        .shadow(color: .black.opacity(0.12), radius: 14, y: 6)
 702    }
 703}
 704
 705struct LookupProgressOverviewView: View {
 706    @Environment(\.appDensity) private var appDensity
 707    let steps: [String]
 708
 709    var body: some View {
 710        CardView(allowsHorizontalScroll: false) {
 711            HStack(spacing: 8) {
 712                ProgressView()
 713                    .controlSize(.small)
 714                VStack(alignment: .leading, spacing: 4) {
 715                    Text("Running lookup…")
 716                        .font(appDensity.font(.caption))
 717                        .foregroundStyle(.primary)
 718                    Text(steps.isEmpty ? "Preparing requests" : steps.joined(separator: " • "))
 719                        .font(appDensity.font(.caption2))
 720                        .foregroundStyle(.secondary)
 721                }
 722                Spacer()
 723            }
 724        }
 725    }
 726}
 727
 728struct LookupStatusBannerView: View {
 729    @Environment(\.appDensity) private var appDensity
 730    let message: String
 731    let resultSource: LookupResultSource
 732
 733    var body: some View {
 734        HStack(spacing: 8) {
 735            Image(systemName: iconName)
 736                .font(.caption)
 737            Text(message)
 738                .font(appDensity.font(.caption))
 739            Spacer()
 740        }
 741        .foregroundStyle(color)
 742        .padding(appDensity.metrics.cardPadding - 2)
 743        .frame(maxWidth: .infinity, alignment: .leading)
 744        .background(color.opacity(0.12))
 745        .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
 746    }
 747
 748    private var color: Color {
 749        switch resultSource {
 750        case .live:
 751            return .green
 752        case .cached:
 753            return .secondary
 754        case .mixed:
 755            return .yellow
 756        case .snapshot:
 757            return .orange
 758        }
 759    }
 760
 761    private var iconName: String {
 762        switch resultSource {
 763        case .live:
 764            return "bolt.horizontal"
 765        case .cached:
 766            return "clock.arrow.trianglehead.counterclockwise.rotate.90"
 767        case .mixed:
 768            return "arrow.triangle.branch"
 769        case .snapshot:
 770            return "archivebox"
 771        }
 772    }
 773}
 774
 775struct DomainChangeSummaryView: View {
 776    @Environment(\.appDensity) private var appDensity
 777    let summary: DomainChangeSummary
 778    @State private var showsDetails = false
 779
 780    var body: some View {
 781        CardView(allowsHorizontalScroll: false) {
 782            HStack {
 783                Label(summary.hasChanges ? "Changed" : "Stable", systemImage: summary.hasChanges ? "arrow.triangle.2.circlepath" : "checkmark.circle")
 784                    .font(appDensity.font(.caption))
 785                    .foregroundStyle(summary.hasChanges ? severityColor(summary.severity) : .green)
 786                Spacer()
 787                Text(summary.severity.title.uppercased())
 788                    .font(appDensity.font(.caption2))
 789                    .foregroundStyle(summary.hasChanges ? severityColor(summary.severity) : .secondary)
 790                    .padding(.horizontal, 8)
 791                    .padding(.vertical, 4)
 792                    .background((summary.hasChanges ? severityColor(summary.severity) : .secondary).opacity(0.16))
 793                    .clipShape(Capsule())
 794                Text(summary.generatedAt, style: .time)
 795                    .font(appDensity.font(.caption2))
 796                    .foregroundStyle(.secondary)
 797            }
 798
 799            VStack(alignment: .leading, spacing: 4) {
 800                Text("Inference")
 801                    .font(appDensity.font(.caption2))
 802                    .foregroundStyle(.secondary)
 803                Text(summary.message)
 804                    .font(appDensity.font(.caption))
 805                    .foregroundStyle(.primary)
 806                    .lineLimit(2)
 807            }
 808
 809            if !summary.observedFacts.isEmpty || summary.contextNote != nil {
 810                DisclosureGroup(showsDetails ? "Hide Details" : "Show Details", isExpanded: $showsDetails) {
 811                    VStack(alignment: .leading, spacing: 8) {
 812                        if !summary.observedFacts.isEmpty {
 813                            VStack(alignment: .leading, spacing: 4) {
 814                                Text("Observed")
 815                                    .font(appDensity.font(.caption2))
 816                                    .foregroundStyle(.secondary)
 817                                ForEach(Array(summary.observedFacts.enumerated()), id: \.offset) { _, fact in
 818                                    Text(fact)
 819                                        .font(appDensity.font(.caption))
 820                                        .foregroundStyle(.primary)
 821                                }
 822                            }
 823                        }
 824
 825                        if let contextNote = summary.contextNote {
 826                            Text(contextNote)
 827                                .font(appDensity.font(.caption2))
 828                                .foregroundStyle(.orange)
 829                        }
 830                    }
 831                    .padding(.top, 4)
 832                }
 833                .font(appDensity.font(.caption))
 834                .tint(.secondary)
 835            }
 836        }
 837    }
 838
 839    private func severityColor(_ severity: ChangeSeverity) -> Color {
 840        switch severity {
 841        case .low:
 842            return .secondary
 843        case .medium:
 844            return .yellow
 845        case .high:
 846            return .red
 847        }
 848    }
 849}
 850
 851struct DomainDiffView: View {
 852    let title: String
 853    let sections: [DomainDiffSection]
 854    let contextNote: String?
 855    let showsUnchanged: Bool
 856
 857    @State private var collapsedSections = Set<UUID>()
 858    @State private var showsLowSeverity = false
 859
 860    private var filteredSections: [DomainDiffSection] {
 861        sections
 862            .map { section in
 863                let items = section.items.filter { item in
 864                    if !showsUnchanged, !item.hasChanges {
 865                        return false
 866                    }
 867                    if showsLowSeverity {
 868                        return true
 869                    }
 870                    return item.severity >= .medium || (showsUnchanged && item.changeType == .unchanged)
 871                }
 872                return DomainDiffSection(title: section.title, items: items)
 873            }
 874            .filter { !$0.items.isEmpty }
 875    }
 876
 877    private var hasLowSeverityChanges: Bool {
 878        sections.flatMap(\.items).contains { $0.hasChanges && $0.severity == .low }
 879    }
 880
 881    var body: some View {
 882        VStack(alignment: .leading, spacing: 12) {
 883            HStack {
 884                SectionTitleView(title: title)
 885                Spacer()
 886                if hasLowSeverityChanges {
 887                    Button(showsLowSeverity ? "Hide Low" : "Show Low") {
 888                        showsLowSeverity.toggle()
 889                    }
 890                    .buttonStyle(.bordered)
 891                    .font(.system(.caption, design: .monospaced))
 892                }
 893            }
 894            if let contextNote {
 895                MessageCardView(text: contextNote, isError: false)
 896            }
 897            if filteredSections.isEmpty {
 898                MessageCardView(text: "No comparison data available", isError: false)
 899            } else {
 900                ForEach(filteredSections) { section in
 901                    CardView(allowsHorizontalScroll: false) {
 902                        DisclosureGroup(isExpanded: binding(for: section)) {
 903                            let visibleItems = showsUnchanged ? section.items : section.items.filter(\.hasChanges)
 904
 905                            ForEach(visibleItems) { item in
 906                                VStack(alignment: .leading, spacing: 6) {
 907                                    HStack {
 908                                        Text(item.label)
 909                                            .font(.system(.caption, design: .monospaced))
 910                                            .foregroundStyle(.secondary)
 911                                        Spacer()
 912                                        Text("\(item.severity.title) • \(changeLabel(for: item.changeType))")
 913                                            .font(.system(.caption2, design: .monospaced))
 914                                            .foregroundStyle(changeColor(for: item))
 915                                            .padding(.horizontal, 8)
 916                                            .padding(.vertical, 4)
 917                                            .background(changeColor(for: item).opacity(0.16))
 918                                            .clipShape(Capsule())
 919                                    }
 920
 921                                    if let oldValue = item.oldValue {
 922                                        VStack(alignment: .leading, spacing: 2) {
 923                                            Text("Old")
 924                                                .font(.system(.caption2, design: .monospaced))
 925                                                .foregroundStyle(.secondary)
 926                                            Text(oldValue)
 927                                                .font(.system(.caption2, design: .monospaced))
 928                                                .foregroundStyle(.secondary)
 929                                                .textSelection(.enabled)
 930                                        }
 931                                    }
 932
 933                                    if let newValue = item.newValue {
 934                                        VStack(alignment: .leading, spacing: 2) {
 935                                            Text("New")
 936                                                .font(.system(.caption2, design: .monospaced))
 937                                                .foregroundStyle(.secondary)
 938                                            Text(newValue)
 939                                                .font(.system(.caption, design: .monospaced))
 940                                                .foregroundStyle(item.hasChanges ? .primary : .secondary)
 941                                                .textSelection(.enabled)
 942                                        }
 943                                    }
 944                                }
 945                                .padding(10)
 946                                .background(item.hasChanges ? changeColor(for: item).opacity(0.08) : Color(.systemGray6).opacity(0.25))
 947                                .cornerRadius(8)
 948                            }
 949                        } label: {
 950                            HStack {
 951                                Text(section.title)
 952                                    .font(.system(.subheadline, design: .monospaced))
 953                                    .fontWeight(.semibold)
 954                                    .foregroundStyle(sectionColor(section))
 955                                Spacer()
 956                                Text(section.severity.title)
 957                                    .font(.system(.caption2, design: .monospaced))
 958                                    .foregroundStyle(sectionColor(section))
 959                            }
 960                        }
 961                    }
 962                }
 963            }
 964        }
 965    }
 966
 967    private func changeLabel(for changeType: DiffChangeType) -> String {
 968        switch changeType {
 969        case .added:
 970            return "Added"
 971        case .removed:
 972            return "Removed"
 973        case .changed:
 974            return "Changed"
 975        case .unchanged:
 976            return "Unchanged"
 977        }
 978    }
 979
 980    private func changeColor(for item: DomainDiffItem) -> Color {
 981        if item.changeType == .unchanged {
 982            return .secondary
 983        }
 984
 985        switch item.severity {
 986        case .low:
 987            return .blue
 988        case .medium:
 989            return .yellow
 990        case .high:
 991            return .red
 992        }
 993    }
 994
 995    private func sectionColor(_ section: DomainDiffSection) -> Color {
 996        switch section.severity {
 997        case .low:
 998            return .blue
 999        case .medium:
1000            return .yellow
1001        case .high:
1002            return .red
1003        }
1004    }
1005
1006    private func binding(for section: DomainDiffSection) -> Binding<Bool> {
1007        Binding(
1008            get: { !collapsedSections.contains(section.id) },
1009            set: { isExpanded in
1010                if isExpanded {
1011                    collapsedSections.remove(section.id)
1012                } else {
1013                    collapsedSections.insert(section.id)
1014                }
1015            }
1016        )
1017    }
1018}
1019
1020struct TrackedDomainDetailHeaderView: View {
1021    let trackedDomain: TrackedDomain
1022
1023    var body: some View {
1024        VStack(alignment: .leading, spacing: 4) {
1025            if let note = trackedDomain.note?.nilIfEmpty {
1026                LabeledValueRow(row: InfoRowViewData(label: "Tracking Note", value: note, tone: .secondary))
1027            }
1028            HStack(spacing: 8) {
1029                if trackedDomain.isPinned {
1030                    Label("Pinned", systemImage: "pin.fill")
1031                }
1032                Text("Last refresh \(trackedDomain.updatedAt.formatted(date: .abbreviated, time: .shortened))")
1033            }
1034            .font(.system(.caption2, design: .monospaced))
1035            .foregroundStyle(.secondary)
1036        }
1037    }
1038}
1039
1040struct DomainSectionView: View {
1041    @Environment(\.appDensity) private var appDensity
1042    @Binding var isCollapsed: Bool
1043    let rows: [InfoRowViewData]
1044    let suggestions: [DomainSuggestionViewData]
1045    let showSuggestions: Bool
1046    let availabilityLoading: Bool
1047    let suggestionsLoading: Bool
1048    let provenance: SectionProvenance?
1049    let confidence: ConfidenceLevel?
1050    let snapshotNote: String?
1051    let trackedDomain: TrackedDomain?
1052    let workflows: [DomainWorkflow]
1053    let trackingLimitMessage: String?
1054    let onTrack: () -> Void
1055    let onTogglePinned: () -> Void
1056    let onEditNote: (() -> Void)?
1057    let onAddToWorkflow: (() -> Void)?
1058    let onOpenWorkflow: ((DomainWorkflow) -> Void)?
1059    let onRunWorkflow: ((DomainWorkflow) -> Void)?
1060
1061    var body: some View {
1062        CollapsibleSectionView(title: "Domain", isCollapsed: $isCollapsed) {
1063            if let trackedDomain {
1064                HStack(spacing: 8) {
1065                    AppStatusBadgeView(model: .init(title: "Tracked", systemImage: "eye.fill", foregroundColor: .green, backgroundColor: .green.opacity(0.16)))
1066                    Button {
1067                        onTogglePinned()
1068                    } label: {
1069                        Image(systemName: trackedDomain.isPinned ? "pin.fill" : "pin")
1070                    }
1071                    .buttonStyle(.bordered)
1072                    .font(appDensity.font(.caption))
1073                    if let onEditNote {
1074                        Button("Note") {
1075                            onEditNote()
1076                        }
1077                        .buttonStyle(.bordered)
1078                        .font(appDensity.font(.caption))
1079                    }
1080                }
1081            } else {
1082                Button("Track") {
1083                    AppHaptics.track()
1084                    onTrack()
1085                }
1086                .buttonStyle(.bordered)
1087                .font(appDensity.font(.caption))
1088            }
1089        } content: {
1090            CardView(allowsHorizontalScroll: false) {
1091                SectionTrustMetadataView(
1092                    provenance: provenance,
1093                    confidence: confidence,
1094                    note: snapshotNote == nil ? nil : "Audit note present"
1095                )
1096                ForEach(rows) { row in
1097                    LabeledValueRow(row: row)
1098                }
1099                if let trackedDomain {
1100                    TrackedDomainDetailHeaderView(trackedDomain: trackedDomain)
1101                        .padding(.top, 4)
1102                } else if let trackingLimitMessage {
1103                    MessageRowView(text: trackingLimitMessage, isError: false)
1104                        .padding(.top, 4)
1105                }
1106                if let onAddToWorkflow {
1107                    Button {
1108                        onAddToWorkflow()
1109                    } label: {
1110                        Label("Add to workflow", systemImage: "plus.rectangle.on.folder")
1111                            .font(appDensity.font(.caption))
1112                    }
1113                    .buttonStyle(.bordered)
1114                    .padding(.top, 4)
1115                }
1116                if !workflows.isEmpty {
1117                    VStack(alignment: .leading, spacing: 8) {
1118                        Text("Part of workflow")
1119                            .font(appDensity.font(.caption))
1120                            .foregroundStyle(.secondary)
1121
1122                        ForEach(workflows) { workflow in
1123                            HStack {
1124                                Text(workflow.name)
1125                                    .font(appDensity.font(.caption))
1126                                    .foregroundStyle(.primary)
1127                                Spacer()
1128                                if let onOpenWorkflow {
1129                                    Button("Open") {
1130                                        onOpenWorkflow(workflow)
1131                                    }
1132                                    .buttonStyle(.bordered)
1133                                    .font(appDensity.font(.caption2))
1134                                }
1135                                if let onRunWorkflow {
1136                                    Button("Run") {
1137                                        onRunWorkflow(workflow)
1138                                    }
1139                                    .buttonStyle(.bordered)
1140                                    .font(appDensity.font(.caption2))
1141                                }
1142                            }
1143                        }
1144                    }
1145                    .padding(.top, 4)
1146                }
1147                if availabilityLoading {
1148                    ProgressView("Checking availability…")
1149                        .appLoadingStyle()
1150                        .padding(.top, 4)
1151                }
1152                if showSuggestions {
1153                    Text("Suggestions")
1154                        .font(appDensity.font(.caption))
1155                        .foregroundStyle(.secondary)
1156                        .padding(.top, 4)
1157                    if suggestionsLoading {
1158                        ProgressView("Checking alternatives…")
1159                            .appLoadingStyle()
1160                    } else if suggestions.isEmpty {
1161                        MessageRowView(text: "No suggestions", isError: false)
1162                    } else {
1163                        ForEach(suggestions) { suggestion in
1164                            HStack {
1165                                Text(suggestion.domain)
1166                                    .font(appDensity.font(.caption))
1167                                    .foregroundStyle(.primary)
1168                                    .textSelection(.enabled)
1169                                Spacer()
1170                                AppStatusBadgeView(model: AppStatusFactory.availability(suggestion.availabilityStatus))
1171                            }
1172                        }
1173                    }
1174                }
1175            }
1176        }
1177    }
1178}
1179
1180struct OwnershipSectionView: View {
1181    @Binding var isCollapsed: Bool
1182    let rows: [InfoRowViewData]
1183    let loading: Bool
1184    let error: String?
1185    let provenance: SectionProvenance?
1186    let confidence: ConfidenceLevel?
1187    let showsHistoryPlaceholder: Bool
1188
1189    var body: some View {
1190        CollapsibleSectionView(title: "Ownership", isCollapsed: $isCollapsed) {
1191            CardView(allowsHorizontalScroll: false) {
1192                SectionTrustMetadataView(provenance: provenance, confidence: confidence)
1193                if loading {
1194                    ProgressView("Fetching RDAP ownership…")
1195                        .appLoadingStyle()
1196                } else {
1197                    ForEach(rows) { row in
1198                        LabeledValueRow(row: row)
1199                    }
1200                    if let error, rows.allSatisfy({ $0.value == "Unavailable" }) {
1201                        MessageRowView(text: error, isError: error != "Unavailable")
1202                            .padding(.top, 4)
1203                    }
1204                    if showsHistoryPlaceholder {
1205                        MessageRowView(text: "Ownership history (coming soon)", isError: false)
1206                            .padding(.top, 4)
1207                    }
1208                }
1209            }
1210        }
1211    }
1212}
1213
1214struct SubdomainsSectionView: View {
1215    @Environment(\.appDensity) private var appDensity
1216    @Binding var isCollapsed: Bool
1217    let rows: [SubdomainRowViewData]
1218    let loading: Bool
1219    let error: String?
1220    let provenance: SectionProvenance?
1221    let confidence: ConfidenceLevel?
1222    let showsExtendedPlaceholder: Bool
1223
1224    var body: some View {
1225        CollapsibleSectionView(title: "Subdomains", isCollapsed: $isCollapsed, subtitle: "\(rows.count) found") {
1226            CardView(allowsHorizontalScroll: false) {
1227                SectionTrustMetadataView(provenance: provenance, confidence: confidence)
1228                if loading {
1229                    ProgressView("Checking certificate transparency…")
1230                        .appLoadingStyle()
1231                } else if rows.isEmpty {
1232                    MessageRowView(text: error ?? "No passive subdomains found", isError: false)
1233                    if showsExtendedPlaceholder {
1234                        MessageRowView(text: "Extended subdomain discovery (Data+)", isError: false)
1235                            .padding(.top, 4)
1236                    }
1237                } else {
1238                    ForEach(rows) { row in
1239                        HStack(spacing: 8) {
1240                            Text(row.hostname)
1241                                .font(appDensity.font(.caption))
1242                                .foregroundStyle(.primary)
1243                                .textSelection(.enabled)
1244                            Spacer()
1245                            if row.isInteresting {
1246                                Text("Interesting")
1247                                    .font(.system(.caption2, design: .monospaced))
1248                                    .foregroundStyle(.yellow)
1249                                    .padding(.horizontal, 8)
1250                                    .padding(.vertical, 4)
1251                                    .background(Color.yellow.opacity(0.14))
1252                                    .clipShape(Capsule())
1253                            }
1254                        }
1255                    }
1256                    if showsExtendedPlaceholder {
1257                        MessageRowView(text: "Extended subdomain discovery (Data+)", isError: false)
1258                            .padding(.top, 4)
1259                    }
1260                }
1261            }
1262        }
1263    }
1264}
1265
1266struct DNSSectionView: View {
1267    @Binding var isCollapsed: Bool
1268    let dnssecLabel: String?
1269    let sections: [DNSRecordSectionViewData]
1270    let ptrMessage: SectionMessageViewData?
1271    let loading: Bool
1272    let dnsProvenance: SectionProvenance?
1273    let ptrProvenance: SectionProvenance?
1274    let sectionError: String?
1275
1276    var body: some View {
1277        CollapsibleSectionView(title: "DNS", isCollapsed: $isCollapsed, subtitle: dnssecLabel) {
1278            if loading {
1279                LoadingCardView(text: "Querying DNS…")
1280            } else if let sectionError, sections.isEmpty {
1281                MessageCardView(text: sectionError, isError: true)
1282            } else {
1283                if dnsProvenance != nil {
1284                    CardView(allowsHorizontalScroll: false) {
1285                        SectionTrustMetadataView(provenance: dnsProvenance, confidence: nil)
1286                    }
1287                }
1288                ForEach(sections) { section in
1289                    CardView {
1290                        Text(section.title)
1291                            .font(.system(.subheadline, design: .monospaced))
1292                            .fontWeight(.semibold)
1293                            .foregroundStyle(.cyan)
1294
1295                        if let message = section.message {
1296                            MessageRowView(text: message.text, isError: message.isError)
1297                        }
1298
1299                        ForEach(section.rows) { row in
1300                            LabeledValueRow(row: row)
1301                        }
1302
1303                        if let wildcardTitle = section.wildcardTitle {
1304                            Text(wildcardTitle)
1305                                .font(.system(.caption, design: .monospaced))
1306                                .foregroundStyle(.secondary)
1307                                .padding(.top, 4)
1308                            ForEach(section.wildcardRows) { row in
1309                                LabeledValueRow(row: row)
1310                            }
1311                        }
1312                    }
1313                }
1314
1315                if let ptrMessage {
1316                    CardView {
1317                        Text("PTR")
1318                            .font(.system(.subheadline, design: .monospaced))
1319                            .fontWeight(.semibold)
1320                            .foregroundStyle(.cyan)
1321                        SectionTrustMetadataView(provenance: ptrProvenance, confidence: nil)
1322                        MessageRowView(text: ptrMessage.text, isError: ptrMessage.isError)
1323                    }
1324                }
1325            }
1326        }
1327    }
1328}
1329
1330struct WebSectionView: View {
1331    @Environment(\.appDensity) private var appDensity
1332    @Binding var isCollapsed: Bool
1333    let certificateRows: [InfoRowViewData]
1334    let sslInfo: SSLCertificateInfo?
1335    let sslLoading: Bool
1336    let sslError: String?
1337    let tlsProvenance: SectionProvenance?
1338    let responseRows: [InfoRowViewData]
1339    let headers: [HTTPHeader]
1340    let headersLoading: Bool
1341    let headersError: String?
1342    let httpProvenance: SectionProvenance?
1343    let redirects: [RedirectHopViewData]
1344    let redirectLoading: Bool
1345    let redirectError: String?
1346    let redirectProvenance: SectionProvenance?
1347    let finalURL: String?
1348
1349    var body: some View {
1350        CollapsibleSectionView(title: "Web", isCollapsed: $isCollapsed) {
1351            CardView {
1352                HStack {
1353                    Text("TLS")
1354                        .font(appDensity.font(.subheadline, weight: .semibold))
1355                        .foregroundStyle(.cyan)
1356                    Spacer()
1357                    AppStatusBadgeView(model: AppStatusFactory.tls(sslInfo: sslInfo, error: sslError))
1358                }
1359                SectionTrustMetadataView(provenance: tlsProvenance, confidence: nil)
1360                if sslLoading {
1361                    ProgressView("Checking certificate…")
1362                        .appLoadingStyle()
1363                } else if let sslError {
1364                    MessageRowView(text: sslError, isError: true)
1365                } else {
1366                    ForEach(certificateRows) { row in
1367                        LabeledValueRow(row: row)
1368                    }
1369                    if let sslInfo, !sslInfo.subjectAltNames.isEmpty {
1370                        Text("SANs")
1371                            .font(appDensity.font(.caption2))
1372                            .foregroundStyle(.secondary)
1373                        ForEach(sslInfo.subjectAltNames, id: \.self) { san in
1374                            HStack(spacing: 8) {
1375                                Text(san)
1376                                    .font(appDensity.font(.caption))
1377                                    .textSelection(.enabled)
1378                                Spacer()
1379                                AppCopyButton(value: san, label: "Copy certificate SAN")
1380                            }
1381                        }
1382                    }
1383                }
1384            }
1385
1386            CardView {
1387                Text("Headers")
1388                    .font(appDensity.font(.subheadline, weight: .semibold))
1389                    .foregroundStyle(.cyan)
1390                SectionTrustMetadataView(provenance: httpProvenance, confidence: nil)
1391                if headersLoading {
1392                    ProgressView("Fetching headers…")
1393                        .appLoadingStyle()
1394                } else if let headersError {
1395                    MessageRowView(text: headersError, isError: true)
1396                } else {
1397                    ForEach(responseRows) { row in
1398                        LabeledValueRow(row: row)
1399                    }
1400                    if headers.isEmpty {
1401                        MessageRowView(text: "No HTTP headers returned", isError: false)
1402                    } else {
1403                        ForEach(headers) { header in
1404                            HStack(alignment: .top, spacing: 4) {
1405                                Text(header.name + ":")
1406                                    .font(appDensity.font(.caption))
1407                                    .foregroundStyle(header.isSecurityHeader ? .yellow : .cyan)
1408                                Text(header.value)
1409                                    .font(appDensity.font(.caption))
1410                                    .foregroundStyle(.primary)
1411                                    .textSelection(.enabled)
1412                            }
1413                        }
1414                    }
1415                }
1416            }
1417
1418            CardView {
1419                HStack {
1420                    Text("Redirects")
1421                        .font(appDensity.font(.subheadline, weight: .semibold))
1422                        .foregroundStyle(.cyan)
1423                    Spacer()
1424                    if let finalURL {
1425                        AppCopyButton(value: finalURL, label: "Copy redirect URL")
1426                    }
1427                }
1428                SectionTrustMetadataView(provenance: redirectProvenance, confidence: nil)
1429                if redirectLoading {
1430                    ProgressView("Tracing redirects…")
1431                        .appLoadingStyle()
1432                } else if let redirectError {
1433                    MessageRowView(text: redirectError, isError: true)
1434                } else if redirects.isEmpty {
1435                    MessageRowView(text: "No redirect data available", isError: false)
1436                } else {
1437                    if let finalURL {
1438                        LabeledValueRow(row: InfoRowViewData(label: "Final URL", value: finalURL, tone: .secondary))
1439                    }
1440                    ForEach(redirects) { redirect in
1441                        HStack(alignment: .top, spacing: 6) {
1442                            Text(redirect.stepLabel)
1443                                .font(appDensity.font(.caption))
1444                                .foregroundStyle(.secondary)
1445                                .frame(width: 16, alignment: .trailing)
1446                            Text(redirect.statusCode)
1447                                .font(appDensity.font(.caption))
1448                                .foregroundStyle(.cyan)
1449                                .frame(width: 36, alignment: .leading)
1450                            Text(redirect.url)
1451                                .font(appDensity.font(.caption))
1452                                .textSelection(.enabled)
1453                            AppCopyButton(value: redirect.url, label: "Copy redirect URL")
1454                            if redirect.isFinal {
1455                                Text("(final)")
1456                                    .font(appDensity.font(.caption2))
1457                                    .foregroundStyle(.secondary)
1458                            }
1459                        }
1460                    }
1461                }
1462            }
1463        }
1464    }
1465}
1466
1467struct EmailSectionView: View {
1468    @Environment(\.appDensity) private var appDensity
1469    @Binding var isCollapsed: Bool
1470    let rows: [EmailRowViewData]
1471    let loading: Bool
1472    let provenance: SectionProvenance?
1473    let confidence: ConfidenceLevel?
1474    let error: String?
1475
1476    var body: some View {
1477        CollapsibleSectionView(title: "Email", isCollapsed: $isCollapsed) {
1478            CardView {
1479                SectionTrustMetadataView(provenance: provenance, confidence: confidence)
1480                HStack {
1481                    Spacer()
1482                    AppStatusBadgeView(model: AppStatusFactory.email(nil, error: error))
1483                        .opacity(loading ? 0 : 1)
1484                }
1485                if loading {
1486                    ProgressView("Checking email records…")
1487                        .appLoadingStyle()
1488                } else if let error {
1489                    MessageRowView(text: error, isError: true)
1490                } else if rows.isEmpty {
1491                    MessageRowView(text: "No email security records found", isError: false)
1492                } else {
1493                    ForEach(rows) { row in
1494                        VStack(alignment: .leading, spacing: 4) {
1495                            HStack(spacing: 8) {
1496                                Text(row.label)
1497                                    .font(appDensity.font(.caption))
1498                                    .foregroundStyle(.cyan)
1499                                    .frame(width: 76, alignment: .leading)
1500                                AppStatusBadgeView(model: emailRowBadge(row))
1501                            }
1502                            Text(row.detail)
1503                                .font(appDensity.font(.caption2))
1504                                .foregroundStyle(.primary)
1505                                .textSelection(.enabled)
1506                            if let auxiliaryDetail = row.auxiliaryDetail {
1507                                Text(auxiliaryDetail)
1508                                    .font(appDensity.font(.caption2))
1509                                    .foregroundStyle(.secondary)
1510                            }
1511                        }
1512                    }
1513                }
1514            }
1515        }
1516    }
1517
1518    private func emailRowBadge(_ row: EmailRowViewData) -> AppStatusBadgeModel {
1519        switch row.statusTone {
1520        case .success:
1521            return .init(title: row.status, systemImage: "checkmark.shield.fill", foregroundColor: .green, backgroundColor: .green.opacity(0.16))
1522        case .warning:
1523            return .init(title: row.status, systemImage: "shield.lefthalf.filled", foregroundColor: .yellow, backgroundColor: .yellow.opacity(0.16))
1524        case .failure:
1525            return .init(title: row.status, systemImage: "minus.circle", foregroundColor: .secondary, backgroundColor: Color(.systemGray5).opacity(0.55))
1526        case .primary, .secondary:
1527            return .init(title: row.status, systemImage: "circle", foregroundColor: .secondary, backgroundColor: Color(.systemGray5).opacity(0.55))
1528        }
1529    }
1530}
1531
1532struct NetworkSectionView: View {
1533    @Environment(\.appDensity) private var appDensity
1534    @Binding var isCollapsed: Bool
1535    let reachabilityRows: [ReachabilityRowViewData]
1536    let reachabilityLoading: Bool
1537    let reachabilityError: String?
1538    let reachabilityProvenance: SectionProvenance?
1539    let locationRows: [InfoRowViewData]
1540    let geolocation: IPGeolocation?
1541    let geolocationLoading: Bool
1542    let geolocationError: String?
1543    let geolocationProvenance: SectionProvenance?
1544    let geolocationConfidence: ConfidenceLevel?
1545    let standardPortRows: [PortScanRowViewData]
1546    let customPortRows: [PortScanRowViewData]
1547    let portScanLoading: Bool
1548    let portScanError: String?
1549    let portScanProvenance: SectionProvenance?
1550    let customPortScanLoading: Bool
1551    let customPortScanError: String?
1552    let isCloudflareProxied: Bool
1553    @Binding var customPortsExpanded: Bool
1554    @Binding var customPortInput: String
1555    let onScanCustomPorts: () -> Void
1556
1557    var body: some View {
1558        CollapsibleSectionView(title: "Network", isCollapsed: $isCollapsed) {
1559            CardView {
1560                Text("Reachability")
1561                    .font(appDensity.font(.subheadline, weight: .semibold))
1562                    .foregroundStyle(.cyan)
1563                SectionTrustMetadataView(provenance: reachabilityProvenance, confidence: nil)
1564                if reachabilityLoading {
1565                    ProgressView("Checking ports…")
1566                        .appLoadingStyle()
1567                } else if let reachabilityError {
1568                    MessageRowView(text: reachabilityError, isError: true)
1569                } else {
1570                    ForEach(reachabilityRows) { row in
1571                        HStack {
1572                            Text(row.portLabel)
1573                                .font(appDensity.font(.caption))
1574                            Spacer()
1575                            Text(row.latencyLabel)
1576                                .font(appDensity.font(.caption2))
1577                                .foregroundStyle(.secondary)
1578                            AppStatusBadgeView(model: reachabilityBadge(row))
1579                        }
1580                    }
1581                }
1582            }
1583
1584            CardView(allowsHorizontalScroll: false) {
1585                Text("Location")
1586                    .font(appDensity.font(.subheadline, weight: .semibold))
1587                    .foregroundStyle(.cyan)
1588                SectionTrustMetadataView(provenance: geolocationProvenance, confidence: geolocationConfidence)
1589                if geolocationLoading {
1590                    ProgressView("Looking up location…")
1591                        .appLoadingStyle()
1592                } else if let geolocationError, geolocation == nil {
1593                    MessageRowView(text: geolocationError, isError: geolocationError != "No A record available")
1594                } else if let geolocation {
1595                    ForEach(locationRows) { row in
1596                        LabeledValueRow(row: row)
1597                    }
1598                    if let latitude = geolocation.latitude, let longitude = geolocation.longitude {
1599                        let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
1600                        Map(initialPosition: .region(MKCoordinateRegion(
1601                            center: coordinate,
1602                            span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1)
1603                        ))) {
1604                            Marker(geolocation.ip, coordinate: coordinate)
1605                        }
1606                        .mapStyle(.standard)
1607                        .frame(maxWidth: .infinity)
1608                        .frame(height: 180)
1609                        .cornerRadius(8)
1610                    }
1611                } else {
1612                    MessageRowView(text: "No location data available", isError: false)
1613                }
1614            }
1615
1616            CardView(allowsHorizontalScroll: false) {
1617                Text("Port Scan")
1618                    .font(appDensity.font(.subheadline, weight: .semibold))
1619                    .foregroundStyle(.cyan)
1620                SectionTrustMetadataView(provenance: portScanProvenance, confidence: nil)
1621
1622                if isCloudflareProxied {
1623                    Text("Domain is behind Cloudflare's proxy. Results reflect the edge, not the origin.")
1624                        .font(appDensity.font(.caption2))
1625                        .foregroundStyle(.orange)
1626                        .fixedSize(horizontal: false, vertical: true)
1627                }
1628
1629                if portScanLoading {
1630                    ProgressView("Scanning ports…")
1631                        .appLoadingStyle()
1632                } else if let portScanError, standardPortRows.isEmpty {
1633                    MessageRowView(text: portScanError, isError: true)
1634                } else {
1635                    Text("Standard Ports")
1636                        .font(.system(.caption, design: .monospaced))
1637                        .foregroundStyle(.secondary)
1638                    PortRowsView(rows: standardPortRows)
1639                }
1640
1641                DisclosureGroup("Custom Ports", isExpanded: $customPortsExpanded) {
1642                    VStack(alignment: .leading, spacing: 10) {
1643                        TextField("8888, 9000, 27017", text: $customPortInput)
1644                            .font(appDensity.font(.caption))
1645                            .textInputAutocapitalization(.never)
1646                            .autocorrectionDisabled()
1647                            .keyboardType(.numberPad)
1648                            .padding(10)
1649                            .background(Color(.systemGray6).opacity(0.5))
1650                            .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
1651
1652                        Button("Scan") {
1653                            AppHaptics.refresh()
1654                            onScanCustomPorts()
1655                        }
1656                        .buttonStyle(.borderedProminent)
1657                        .disabled(customPortScanLoading)
1658
1659                        if customPortScanLoading {
1660                            ProgressView("Scanning custom ports…")
1661                                .appLoadingStyle()
1662                        } else if let customPortScanError {
1663                            MessageRowView(text: customPortScanError, isError: true)
1664                        } else {
1665                            PortRowsView(rows: customPortRows)
1666                        }
1667                    }
1668                    .padding(.top, 8)
1669                }
1670                .font(.system(.caption, design: .monospaced))
1671                .tint(.secondary)
1672            }
1673        }
1674    }
1675
1676    private func reachabilityBadge(_ row: ReachabilityRowViewData) -> AppStatusBadgeModel {
1677        switch row.statusTone {
1678        case .success:
1679            return .init(title: row.statusLabel, systemImage: "checkmark.circle.fill", foregroundColor: .green, backgroundColor: .green.opacity(0.16))
1680        case .warning:
1681            return .init(title: row.statusLabel, systemImage: "exclamationmark.triangle.fill", foregroundColor: .yellow, backgroundColor: .yellow.opacity(0.16))
1682        case .failure:
1683            return .init(title: row.statusLabel, systemImage: "xmark.circle.fill", foregroundColor: .red, backgroundColor: .red.opacity(0.16))
1684        case .primary, .secondary:
1685            return .init(title: row.statusLabel, systemImage: "circle", foregroundColor: .secondary, backgroundColor: Color(.systemGray5).opacity(0.55))
1686        }
1687    }
1688}
1689
1690struct PortRowsView: View {
1691    @Environment(\.appDensity) private var appDensity
1692    let rows: [PortScanRowViewData]
1693
1694    var body: some View {
1695        if rows.isEmpty {
1696            MessageRowView(text: "No results", isError: false)
1697        } else {
1698            ForEach(rows) { row in
1699                VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing - 1) {
1700                    HStack {
1701                        Text(row.portLabel)
1702                            .font(appDensity.font(.caption))
1703                            .frame(width: 52, alignment: .leading)
1704                        Text(row.service)
1705                            .font(appDensity.font(.caption))
1706                            .foregroundStyle(.primary)
1707                        Spacer()
1708                        if let durationLabel = row.durationLabel {
1709                            Text(durationLabel)
1710                                .font(appDensity.font(.caption2))
1711                                .foregroundStyle(.secondary)
1712                        }
1713                        AppStatusBadgeView(model: portBadge(row))
1714                    }
1715                    if let banner = row.banner {
1716                        Text(banner)
1717                            .font(appDensity.font(.caption2))
1718                            .foregroundStyle(.secondary)
1719                            .padding(.leading, 8)
1720                    }
1721                }
1722                .frame(minHeight: appDensity.metrics.rowMinHeight, alignment: .topLeading)
1723            }
1724        }
1725    }
1726
1727    private func portBadge(_ row: PortScanRowViewData) -> AppStatusBadgeModel {
1728        switch row.statusTone {
1729        case .success:
1730            return .init(title: row.statusLabel, systemImage: "checkmark.circle.fill", foregroundColor: .green, backgroundColor: .green.opacity(0.16))
1731        case .warning:
1732            return .init(title: row.statusLabel, systemImage: "exclamationmark.triangle.fill", foregroundColor: .yellow, backgroundColor: .yellow.opacity(0.16))
1733        case .failure:
1734            return .init(title: row.statusLabel, systemImage: "xmark.circle.fill", foregroundColor: .red, backgroundColor: .red.opacity(0.16))
1735        case .primary, .secondary:
1736            return .init(title: row.statusLabel, systemImage: "circle", foregroundColor: .secondary, backgroundColor: Color(.systemGray5).opacity(0.55))
1737        }
1738    }
1739}
1740
1741struct SectionTitleView: View {
1742    @Environment(\.appDensity) private var appDensity
1743    let title: String
1744
1745    var body: some View {
1746        Text(title)
1747            .font(appDensity.font(.headline, design: .default, weight: .semibold))
1748            .foregroundStyle(.white)
1749    }
1750}
1751
1752struct CardView<Content: View>: View {
1753    @Environment(\.appDensity) private var appDensity
1754    let allowsHorizontalScroll: Bool
1755    let content: Content
1756
1757    init(allowsHorizontalScroll: Bool = true, @ViewBuilder content: () -> Content) {
1758        self.allowsHorizontalScroll = allowsHorizontalScroll
1759        self.content = content()
1760    }
1761
1762    var body: some View {
1763        Group {
1764            if allowsHorizontalScroll {
1765                ScrollView(.horizontal) {
1766                    cardContent
1767                        .scrollTargetLayout()
1768                }
1769                .scrollBounceBehavior(.basedOnSize, axes: .horizontal)
1770            } else {
1771                cardContent
1772                    .frame(maxWidth: .infinity, alignment: .leading)
1773            }
1774        }
1775        .frame(maxWidth: .infinity, alignment: .leading)
1776        .padding(appDensity.metrics.cardPadding)
1777        .background(Color(.systemGray6).opacity(0.5))
1778        .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
1779    }
1780
1781    private var cardContent: some View {
1782        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
1783            content
1784        }
1785    }
1786}
1787
1788struct LoadingCardView: View {
1789    let text: String
1790
1791    var body: some View {
1792        CardView {
1793            ProgressView(text)
1794                .appLoadingStyle()
1795                .frame(maxWidth: .infinity, alignment: .center)
1796        }
1797    }
1798}
1799
1800struct MessageCardView: View {
1801    let text: String
1802    let isError: Bool
1803
1804    var body: some View {
1805        CardView {
1806            MessageRowView(text: text, isError: isError)
1807        }
1808    }
1809}
1810
1811struct MessageRowView: View {
1812    @Environment(\.appDensity) private var appDensity
1813    let text: String
1814    let isError: Bool
1815
1816    var body: some View {
1817        Label(text, systemImage: isError ? "exclamationmark.triangle.fill" : "info.circle")
1818            .font(appDensity.font(.caption))
1819            .foregroundStyle(isError ? .red : .secondary)
1820    }
1821}
1822
1823struct SectionTrustMetadataView: View {
1824    @Environment(\.appDensity) private var appDensity
1825    let provenance: SectionProvenance?
1826    let confidence: ConfidenceLevel?
1827    let note: String?
1828
1829    init(provenance: SectionProvenance?, confidence: ConfidenceLevel?, note: String? = nil) {
1830        self.provenance = provenance
1831        self.confidence = confidence
1832        self.note = note
1833    }
1834
1835    var body: some View {
1836        if provenance != nil || confidence != nil || note != nil {
1837            VStack(alignment: .leading, spacing: 6) {
1838                HStack(spacing: 8) {
1839                    if let confidence {
1840                        Text("Confidence \(confidence.title)")
1841                            .font(appDensity.font(.caption2))
1842                            .foregroundStyle(.secondary)
1843                    }
1844                    if let provenance {
1845                        Text(provenance.provider ?? provenance.source)
1846                            .font(appDensity.font(.caption2))
1847                            .foregroundStyle(.secondary)
1848                        Text(provenance.resultSource.label)
1849                            .font(appDensity.font(.caption2))
1850                            .foregroundStyle(.secondary)
1851                    }
1852                }
1853                DisclosureGroup("Details") {
1854                    VStack(alignment: .leading, spacing: 4) {
1855                        if let provenance {
1856                            LabeledValueRow(row: .init(label: "Method", value: provenance.source, tone: .secondary))
1857                            if let provider = provenance.provider {
1858                                LabeledValueRow(row: .init(label: "Provider", value: provider, tone: .secondary))
1859                            }
1860                            if let resolver = provenance.resolver {
1861                                LabeledValueRow(row: .init(label: "Resolver", value: resolver, tone: .secondary))
1862                            }
1863                            LabeledValueRow(row: .init(label: "Collected", value: provenance.collectedAt.formatted(date: .abbreviated, time: .shortened), tone: .secondary))
1864                            LabeledValueRow(row: .init(label: "Mode", value: provenance.resultSource.label, tone: .secondary))
1865                        }
1866                        if let note {
1867                            LabeledValueRow(row: .init(label: "Note", value: note, tone: .secondary))
1868                        }
1869                    }
1870                    .padding(.top, 4)
1871                }
1872                .font(appDensity.font(.caption))
1873                .tint(.secondary)
1874            }
1875        }
1876    }
1877}
1878
1879struct LabeledValueRow: View {
1880    @Environment(\.appDensity) private var appDensity
1881    let row: InfoRowViewData
1882
1883    var body: some View {
1884        VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing - 1) {
1885            HStack(alignment: .top, spacing: 8) {
1886                VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing - 1) {
1887                    Text(row.label)
1888                        .font(appDensity.font(.caption2))
1889                        .foregroundStyle(.secondary)
1890                    Text(row.value)
1891                        .font(appDensity.font(.caption))
1892                        .foregroundStyle(ResultColors.color(for: row.tone))
1893                        .textSelection(.enabled)
1894                }
1895                Spacer(minLength: 6)
1896                if !row.value.isEmpty, row.value != "Unavailable" {
1897                    AppCopyButton(value: row.value, label: "Copy \(row.label)")
1898                }
1899            }
1900        }
1901        .frame(minHeight: appDensity.metrics.rowMinHeight, alignment: .topLeading)
1902    }
1903}
1904
1905enum ResultColors {
1906    static func color(for tone: ResultTone) -> Color {
1907        switch tone {
1908        case .primary:
1909            return .primary
1910        case .secondary:
1911            return .secondary
1912        case .success:
1913            return .green
1914        case .warning:
1915            return .yellow
1916        case .failure:
1917            return .red
1918        }
1919    }
1920}
1921
1922extension DateFormatter {
1923    static let certDate: DateFormatter = {
1924        let formatter = DateFormatter()
1925        formatter.dateStyle = .medium
1926        formatter.timeStyle = .short
1927        return formatter
1928    }()
1929}
1930
1931private extension View {
1932    func appLoadingStyle() -> some View {
1933        font(.system(.caption, design: .monospaced))
1934    }
1935}
1936
1937private extension String {
1938    var nilIfEmpty: String? {
1939        isEmpty ? nil : self
1940    }
1941}
1942
1943private struct SettingsView: View {
1944    @Environment(\.appDensity) private var appDensity
1945    @Bindable var viewModel: DomainViewModel
1946    @AppStorage(DNSResolverOption.userDefaultsKey)
1947    private var storedResolverURL = DNSResolverOption.defaultURLString
1948    @AppStorage(AppDensity.userDefaultsKey)
1949    private var storedDensity = AppDensity.compact.rawValue
1950
1951    @State private var resolverOption: DNSResolverOption = .cloudflare
1952    @State private var customResolverURL = DNSResolverOption.defaultURLString
1953    @State private var showClearHistoryConfirmation = false
1954    @State private var showClearCacheConfirmation = false
1955
1956    private var customResolverError: String? {
1957        guard resolverOption == .custom else {
1958            return nil
1959        }
1960        return DNSResolverOption.isValidCustomURL(customResolverURL) ? nil : "Resolver URL must start with https://"
1961    }
1962
1963    var body: some View {
1964        Form {
1965            Section("Display") {
1966                Picker("Density", selection: $storedDensity) {
1967                    ForEach(AppDensity.allCases) { density in
1968                        Text(density.title).tag(density.rawValue)
1969                    }
1970                }
1971            }
1972
1973            Section("Network") {
1974                Picker("Resolver", selection: $resolverOption) {
1975                    ForEach(DNSResolverOption.allCases) { option in
1976                        Text(option.title).tag(option)
1977                    }
1978                }
1979
1980                if resolverOption == .custom {
1981                    TextField("https://resolver.example/dns-query", text: $customResolverURL)
1982                        .textInputAutocapitalization(.never)
1983                        .autocorrectionDisabled()
1984                        .keyboardType(.URL)
1985
1986                    if let customResolverError {
1987                        Text(customResolverError)
1988                            .font(appDensity.font(.caption, design: .default))
1989                            .foregroundStyle(.red)
1990                    }
1991                }
1992            }
1993
1994            Section("Data") {
1995                Button("Clear History", role: .destructive) {
1996                    showClearHistoryConfirmation = true
1997                }
1998
1999                Button("Clear Cache", role: .destructive) {
2000                    showClearCacheConfirmation = true
2001                }
2002            }
2003
2004            Section("About") {
2005                LabeledContent("Version", value: appVersion)
2006                LabeledContent("Storage", value: "Local-only")
2007            }
2008        }
2009        .navigationTitle("Settings")
2010        .alert("Clear history?", isPresented: $showClearHistoryConfirmation) {
2011            Button("Clear", role: .destructive) {
2012                viewModel.clearHistory()
2013            }
2014            Button("Cancel", role: .cancel) {}
2015        } message: {
2016            Text("This removes saved lookup snapshots from this device.")
2017        }
2018        .alert("Clear cache?", isPresented: $showClearCacheConfirmation) {
2019            Button("Clear", role: .destructive) {
2020                viewModel.clearLookupCache()
2021            }
2022            Button("Cancel", role: .cancel) {}
2023        } message: {
2024            Text("This clears the in-memory lookup cache and cancels any cached in-flight work.")
2025        }
2026        .onAppear {
2027            let currentResolverURL = storedResolverURL.trimmingCharacters(in: .whitespacesAndNewlines)
2028            resolverOption = DNSResolverOption.option(for: currentResolverURL)
2029            customResolverURL = resolverOption == .custom ? currentResolverURL : DNSResolverOption.defaultURLString
2030        }
2031        .onChange(of: resolverOption) { _, newValue in
2032            guard let presetURL = newValue.urlString else {
2033                storedResolverURL = customResolverURL.trimmingCharacters(in: .whitespacesAndNewlines)
2034                return
2035            }
2036            storedResolverURL = presetURL
2037        }
2038        .onChange(of: customResolverURL) { _, newValue in
2039            guard resolverOption == .custom else { return }
2040            storedResolverURL = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
2041        }
2042    }
2043
2044    private var appVersion: String {
2045        AppVersion.current
2046    }
2047}
2048
2049#Preview {
2050    ContentView()
2051}