DomainDig/ContentView.swift

22ecca12b4fe0e0850401754c674632f322d919d
domain-dig/DomainDig/ContentView.swift history · blame · raw

1477 lines · 59979 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
  11struct ContentView: View {
  12    @State private var viewModel = DomainViewModel()
  13    @State private var navigationPath = NavigationPath()
  14    @FocusState private var domainFieldFocused: Bool
  15    @State private var customPortInput = ""
  16    @State private var customPortsExpanded = false
  17    @State private var trackingNoteDraft = ""
  18    @State private var editingTrackedDomain: TrackedDomain?
  19    @State private var showTrackLimitAlert = false
  20    @State private var inputMode: LookupInputMode = .single
  21
  22    var body: some View {
  23        NavigationStack(path: $navigationPath) {
  24            ScrollView(.vertical) {
  25                VStack(spacing: 0) {
  26                    inputSection
  27                    if !viewModel.batchResults.isEmpty || viewModel.batchLookupRunning {
  28                        batchSection
  29                            .padding(.top, 8)
  30                    }
  31                    if viewModel.hasRun {
  32                        actionButtons
  33                        SummaryView(fields: viewModel.summaryFields)
  34                            .padding(.top, 8)
  35                        if let changeSummary = viewModel.currentChangeSummary {
  36                            DomainChangeSummaryView(summary: changeSummary)
  37                                .padding(.top, 12)
  38                        }
  39                        DomainSectionView(
  40                            rows: viewModel.domainRows,
  41                            suggestions: viewModel.suggestionRows,
  42                            showSuggestions: viewModel.availabilityResult?.status == .registered || viewModel.suggestionsLoading,
  43                            availabilityLoading: viewModel.availabilityLoading,
  44                            suggestionsLoading: viewModel.suggestionsLoading,
  45                            trackedDomain: viewModel.currentTrackedDomain,
  46                            trackingLimitMessage: viewModel.trackingLimitMessage,
  47                            onTrack: {
  48                                if !viewModel.trackCurrentDomain() {
  49                                    showTrackLimitAlert = true
  50                                }
  51                            },
  52                            onTogglePinned: {
  53                                guard let trackedDomain = viewModel.currentTrackedDomain else { return }
  54                                viewModel.togglePinned(for: trackedDomain)
  55                            },
  56                            onEditNote: {
  57                                guard let trackedDomain = viewModel.currentTrackedDomain else { return }
  58                                trackingNoteDraft = trackedDomain.note ?? ""
  59                                editingTrackedDomain = trackedDomain
  60                            }
  61                        )
  62                            .padding(.top, 16)
  63                        OwnershipSectionView(
  64                            rows: viewModel.ownershipRows,
  65                            loading: viewModel.ownershipLoading,
  66                            error: viewModel.ownershipError,
  67                            showsHistoryPlaceholder: !DataAccessService.hasAccess(to: .ownershipHistory)
  68                        )
  69                        .padding(.top, 16)
  70                        SubdomainsSectionView(
  71                            rows: viewModel.subdomainRows,
  72                            loading: viewModel.subdomainsLoading,
  73                            error: viewModel.subdomainsError,
  74                            showsExtendedPlaceholder: !DataAccessService.hasAccess(to: .extendedSubdomains)
  75                        )
  76                        .padding(.top, 16)
  77                        if !viewModel.currentDiffSections.isEmpty {
  78                            DomainDiffView(
  79                                title: "Latest Changes",
  80                                sections: viewModel.currentDiffSections,
  81                                showsUnchanged: false
  82                            )
  83                            .padding(.top, 16)
  84                        }
  85                        DNSSectionView(
  86                            dnssecLabel: viewModel.dnssecLabel,
  87                            sections: viewModel.dnsRows,
  88                            ptrMessage: viewModel.ptrMessage,
  89                            loading: viewModel.dnsLoading || viewModel.ptrLoading,
  90                            sectionError: viewModel.dnsError
  91                        )
  92                        .padding(.top, 16)
  93                        WebSectionView(
  94                            certificateRows: viewModel.webCertificateRows,
  95                            sslInfo: viewModel.sslInfo,
  96                            sslLoading: viewModel.sslLoading || viewModel.hstsLoading,
  97                            sslError: viewModel.sslError,
  98                            responseRows: viewModel.webResponseRows,
  99                            headers: viewModel.httpHeaders,
 100                            headersLoading: viewModel.httpHeadersLoading,
 101                            headersError: viewModel.httpHeadersError,
 102                            redirects: viewModel.redirectRows,
 103                            redirectLoading: viewModel.redirectChainLoading,
 104                            redirectError: viewModel.redirectChainError,
 105                            finalURL: viewModel.currentSnapshot.redirectChain.last?.url
 106                        )
 107                        .padding(.top, 16)
 108                        EmailSectionView(
 109                            rows: viewModel.emailRows,
 110                            loading: viewModel.emailSecurityLoading,
 111                            error: viewModel.emailSecurityError
 112                        )
 113                        .padding(.top, 16)
 114                        NetworkSectionView(
 115                            reachabilityRows: viewModel.reachabilityRows,
 116                            reachabilityLoading: viewModel.reachabilityLoading,
 117                            reachabilityError: viewModel.reachabilityError,
 118                            locationRows: viewModel.locationRows,
 119                            geolocation: viewModel.ipGeolocation,
 120                            geolocationLoading: viewModel.ipGeolocationLoading,
 121                            geolocationError: viewModel.ipGeolocationError,
 122                            standardPortRows: viewModel.standardPortRows,
 123                            customPortRows: viewModel.customPortRows,
 124                            portScanLoading: viewModel.portScanLoading,
 125                            portScanError: viewModel.portScanError,
 126                            customPortScanLoading: viewModel.customPortScanLoading,
 127                            customPortScanError: viewModel.customPortScanError,
 128                            isCloudflareProxied: viewModel.isCloudflareProxied,
 129                            customPortsExpanded: $customPortsExpanded,
 130                            customPortInput: $customPortInput,
 131                            onScanCustomPorts: runCustomPortScan
 132                        )
 133                        .padding(.top, 16)
 134                    } else if !viewModel.recentSearches.isEmpty {
 135                        recentSearchesSection
 136                    }
 137                }
 138                .padding(.horizontal)
 139                .padding(.bottom, 32)
 140            }
 141            .background(Color.black)
 142            .navigationTitle("DomainDig")
 143            .toolbarColorScheme(.dark, for: .navigationBar)
 144            .preferredColorScheme(.dark)
 145            .toolbar {
 146                ToolbarItemGroup(placement: .topBarTrailing) {
 147                    if viewModel.hasRun {
 148                        Button {
 149                            viewModel.reset()
 150                        } label: {
 151                            Image(systemName: "xmark.circle")
 152                                .foregroundStyle(.secondary)
 153                        }
 154                    }
 155                    NavigationLink {
 156                        WatchlistView(viewModel: viewModel)
 157                    } label: {
 158                        Image(systemName: "eye")
 159                            .foregroundStyle(.secondary)
 160                    }
 161                    Menu {
 162                        NavigationLink {
 163                            HistoryView(viewModel: viewModel)
 164                        } label: {
 165                            Label("History", systemImage: "clock.arrow.trianglehead.counterclockwise.rotate.90")
 166                        }
 167
 168                        NavigationLink {
 169                            SavedDomainsView(viewModel: viewModel)
 170                        } label: {
 171                            Label("Saved Domains", systemImage: "bookmark")
 172                        }
 173
 174                        NavigationLink {
 175                            SettingsView()
 176                        } label: {
 177                            Label("Settings", systemImage: "gearshape")
 178                        }
 179                    } label: {
 180                        Image(systemName: "ellipsis.circle")
 181                            .foregroundStyle(.secondary)
 182                    }
 183                }
 184            }
 185        }
 186        .onAppear {
 187            domainFieldFocused = true
 188        }
 189        .onChange(of: viewModel.rerunNavigationToken) { _, _ in
 190            navigationPath = NavigationPath()
 191            domainFieldFocused = false
 192        }
 193        .alert("Tracking limit reached", isPresented: $showTrackLimitAlert) {
 194            Button("OK", role: .cancel) {}
 195        } message: {
 196            Text("Free version supports up to 3 tracked domains. More tracked domains will be available in a future Pro upgrade.")
 197        }
 198        .sheet(item: $editingTrackedDomain) { trackedDomain in
 199            NavigationStack {
 200                Form {
 201                    Section("Tracking Note") {
 202                        TextField("Optional note", text: $trackingNoteDraft, axis: .vertical)
 203                            .lineLimit(3...6)
 204                            .textInputAutocapitalization(.never)
 205                            .autocorrectionDisabled()
 206                    }
 207                }
 208                .navigationTitle(trackedDomain.domain)
 209                .toolbar {
 210                    ToolbarItem(placement: .cancellationAction) {
 211                        Button("Cancel") {
 212                            editingTrackedDomain = nil
 213                        }
 214                    }
 215                    ToolbarItem(placement: .confirmationAction) {
 216                        Button("Save") {
 217                            viewModel.updateNote(trackingNoteDraft, for: trackedDomain)
 218                            editingTrackedDomain = nil
 219                        }
 220                    }
 221                }
 222            }
 223        }
 224    }
 225
 226    private var inputSection: some View {
 227        VStack(spacing: 12) {
 228            Picker("Mode", selection: $inputMode) {
 229                Text("Single").tag(LookupInputMode.single)
 230                Text("Bulk").tag(LookupInputMode.bulk)
 231            }
 232            .pickerStyle(.segmented)
 233
 234            if inputMode == .single {
 235                TextField("e.g. cleberg.net", text: $viewModel.domain)
 236                    .font(.system(.title3, design: .monospaced))
 237                    .textInputAutocapitalization(.never)
 238                    .autocorrectionDisabled()
 239                    .keyboardType(.URL)
 240                    .padding(12)
 241                    .background(Color(.systemGray6))
 242                    .cornerRadius(8)
 243                    .focused($domainFieldFocused)
 244                    .onSubmit { viewModel.run() }
 245
 246                Button {
 247                    domainFieldFocused = false
 248                    viewModel.run()
 249                } label: {
 250                    Text("Run")
 251                        .font(.headline)
 252                        .frame(maxWidth: .infinity)
 253                        .padding(.vertical, 12)
 254                }
 255                .buttonStyle(.borderedProminent)
 256                .disabled(viewModel.trimmedDomain.isEmpty)
 257            } else {
 258                VStack(alignment: .leading, spacing: 8) {
 259                    Text("Paste domains separated by new lines or commas.")
 260                        .font(.system(.caption, design: .monospaced))
 261                        .foregroundStyle(.secondary)
 262
 263                    TextField(
 264                        "example.com\napple.com, openai.com",
 265                        text: $viewModel.bulkInput,
 266                        axis: .vertical
 267                    )
 268                    .font(.system(.body, design: .monospaced))
 269                    .textInputAutocapitalization(.never)
 270                    .autocorrectionDisabled()
 271                    .keyboardType(.URL)
 272                    .lineLimit(4...10)
 273                    .padding(12)
 274                    .background(Color(.systemGray6))
 275                    .cornerRadius(8)
 276
 277                    Button {
 278                        domainFieldFocused = false
 279                        viewModel.runBulkLookup()
 280                    } label: {
 281                        Text(viewModel.batchLookupRunning ? "Running Batch…" : "Run Batch")
 282                            .font(.headline)
 283                            .frame(maxWidth: .infinity)
 284                            .padding(.vertical, 12)
 285                    }
 286                    .buttonStyle(.borderedProminent)
 287                    .disabled(viewModel.bulkInput.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || viewModel.batchLookupRunning)
 288                }
 289            }
 290        }
 291        .padding(.vertical, 16)
 292    }
 293
 294    private var actionButtons: some View {
 295        HStack {
 296            Spacer()
 297            if viewModel.resultsLoaded {
 298                Button {
 299                    viewModel.toggleSavedDomain()
 300                } label: {
 301                    Image(systemName: viewModel.isCurrentDomainSaved ? "bookmark.fill" : "bookmark")
 302                        .font(.system(.body))
 303                        .foregroundStyle(viewModel.isCurrentDomainSaved ? .yellow : .secondary)
 304                }
 305                Menu {
 306                    Button("Export TXT") {
 307                        shareSingleResults(asCSV: false)
 308                    }
 309                    Button("Export CSV") {
 310                        shareSingleResults(asCSV: true)
 311                    }
 312                } label: {
 313                    Image(systemName: "square.and.arrow.up")
 314                        .font(.system(.body))
 315                        .foregroundStyle(.secondary)
 316                }
 317            }
 318        }
 319    }
 320
 321    private var batchSection: some View {
 322        VStack(alignment: .leading, spacing: 12) {
 323            HStack {
 324                Spacer()
 325                if viewModel.batchLookupRunning {
 326                    Button("Cancel") {
 327                        viewModel.cancelBatchLookup()
 328                    }
 329                    .buttonStyle(.bordered)
 330                    .font(.system(.caption, design: .monospaced))
 331                }
 332                if !viewModel.currentBatchResultEntries.isEmpty {
 333                    Menu {
 334                        Button("Export Batch TXT") {
 335                            shareBatchResults(asCSV: false)
 336                        }
 337                        Button("Export Batch CSV") {
 338                            shareBatchResults(asCSV: true)
 339                        }
 340                    } label: {
 341                        Label("Export", systemImage: "square.and.arrow.up")
 342                            .font(.system(.caption, design: .monospaced))
 343                    }
 344                    .buttonStyle(.bordered)
 345                }
 346            }
 347
 348            BatchResultsView(
 349                viewModel: viewModel,
 350                title: viewModel.batchLookupSource == .watchlistRefresh ? "Tracked Domain Refresh" : "Batch Results"
 351            )
 352        }
 353    }
 354
 355    private var recentSearchesSection: some View {
 356        VStack(alignment: .leading, spacing: 8) {
 357            HStack {
 358                Text("RECENT")
 359                    .font(.system(.caption2, design: .monospaced))
 360                    .foregroundStyle(.secondary)
 361                Spacer()
 362                Button("Clear") {
 363                    viewModel.clearRecentSearches()
 364                }
 365                .font(.system(.caption2, design: .monospaced))
 366                .foregroundStyle(.secondary)
 367            }
 368
 369            ForEach(viewModel.recentSearches, id: \.self) { domain in
 370                Button {
 371                    viewModel.domain = domain
 372                    domainFieldFocused = false
 373                    viewModel.run()
 374                } label: {
 375                    Text(domain)
 376                        .font(.system(.callout, design: .monospaced))
 377                        .foregroundStyle(.primary)
 378                        .frame(maxWidth: .infinity, alignment: .leading)
 379                        .padding(.vertical, 6)
 380                        .padding(.horizontal, 10)
 381                        .background(Color(.systemGray6).opacity(0.5))
 382                        .cornerRadius(6)
 383                }
 384            }
 385        }
 386        .padding(.top, 8)
 387    }
 388
 389    private func runCustomPortScan() {
 390        let ports = parsedCustomPorts(from: customPortInput)
 391        Task {
 392            await viewModel.runCustomPortScan(ports: ports)
 393        }
 394    }
 395
 396    private func parsedCustomPorts(from input: String) -> [UInt16] {
 397        let parts = input.split(separator: ",", omittingEmptySubsequences: true)
 398        var seen = Set<UInt16>()
 399        var ports: [UInt16] = []
 400
 401        for part in parts {
 402            let trimmed = part.trimmingCharacters(in: .whitespacesAndNewlines)
 403            guard let value = UInt16(trimmed), seen.insert(value).inserted else {
 404                continue
 405            }
 406            ports.append(value)
 407            if ports.count == 20 {
 408                break
 409            }
 410        }
 411
 412        return ports
 413    }
 414
 415    private func shareSingleResults(asCSV: Bool) {
 416        let (filename, contents) = exportPayload(
 417            prefix: "domaindig_single",
 418            text: viewModel.exportText(),
 419            csv: viewModel.exportCSV(),
 420            asCSV: asCSV
 421        )
 422        ExportPresenter.share(filename: filename, contents: contents)
 423    }
 424
 425    private func shareBatchResults(asCSV: Bool) {
 426        let (filename, contents) = exportPayload(
 427            prefix: "domaindig_batch",
 428            text: viewModel.exportBatchText(),
 429            csv: viewModel.exportBatchCSV(),
 430            asCSV: asCSV
 431        )
 432        ExportPresenter.share(filename: filename, contents: contents)
 433    }
 434
 435    private func exportPayload(prefix: String, text: String, csv: String, asCSV: Bool) -> (String, String) {
 436        let formatter = DateFormatter()
 437        formatter.dateFormat = "yyyyMMdd_HHmmss"
 438        let timestamp = formatter.string(from: Date())
 439        let fileExtension = asCSV ? "csv" : "txt"
 440        let filename = "\(timestamp)_\(prefix).\(fileExtension)"
 441        return (filename, asCSV ? csv : text)
 442    }
 443}
 444
 445struct SummaryView: View {
 446    let fields: [SummaryFieldViewData]
 447
 448    var body: some View {
 449        VStack(alignment: .leading, spacing: 12) {
 450            SectionTitleView(title: "Summary")
 451            LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 8) {
 452                ForEach(fields) { field in
 453                    VStack(alignment: .leading, spacing: 4) {
 454                        Text(field.label)
 455                            .font(.system(.caption2, design: .monospaced))
 456                            .foregroundStyle(.secondary)
 457                        Text(field.value)
 458                            .font(.system(.caption, design: .monospaced))
 459                            .foregroundStyle(ResultColors.color(for: field.tone))
 460                            .lineLimit(2)
 461                            .textSelection(.enabled)
 462                    }
 463                    .frame(maxWidth: .infinity, alignment: .leading)
 464                    .padding(10)
 465                    .background(Color(.systemGray6).opacity(0.5))
 466                    .cornerRadius(6)
 467                }
 468            }
 469        }
 470    }
 471}
 472
 473struct DomainChangeSummaryView: View {
 474    let summary: DomainChangeSummary
 475
 476    var body: some View {
 477        CardView(allowsHorizontalScroll: false) {
 478            HStack {
 479                Label(summary.hasChanges ? "Changed" : "Stable", systemImage: summary.hasChanges ? "arrow.triangle.2.circlepath" : "checkmark.circle")
 480                    .font(.system(.caption, design: .monospaced))
 481                    .foregroundStyle(summary.hasChanges ? severityColor(summary.severity) : .green)
 482                Spacer()
 483                Text(summary.severity.title.uppercased())
 484                    .font(.system(.caption2, design: .monospaced))
 485                    .foregroundStyle(summary.hasChanges ? severityColor(summary.severity) : .secondary)
 486                    .padding(.horizontal, 8)
 487                    .padding(.vertical, 4)
 488                    .background((summary.hasChanges ? severityColor(summary.severity) : .secondary).opacity(0.16))
 489                    .clipShape(Capsule())
 490                Text(summary.generatedAt, style: .time)
 491                    .font(.system(.caption2, design: .monospaced))
 492                    .foregroundStyle(.secondary)
 493            }
 494
 495            Text(summary.message)
 496                .font(.system(.caption, design: .monospaced))
 497                .foregroundStyle(.primary)
 498        }
 499    }
 500
 501    private func severityColor(_ severity: ChangeSeverity) -> Color {
 502        switch severity {
 503        case .low:
 504            return .secondary
 505        case .medium:
 506            return .yellow
 507        case .high:
 508            return .red
 509        }
 510    }
 511}
 512
 513struct DomainDiffView: View {
 514    let title: String
 515    let sections: [DomainDiffSection]
 516    let showsUnchanged: Bool
 517
 518    @State private var collapsedSections = Set<UUID>()
 519    @State private var showsLowSeverity = false
 520
 521    private var filteredSections: [DomainDiffSection] {
 522        sections
 523            .map { section in
 524                let items = section.items.filter { item in
 525                    if !showsUnchanged, !item.hasChanges {
 526                        return false
 527                    }
 528                    if showsLowSeverity {
 529                        return true
 530                    }
 531                    return item.severity >= .medium || (showsUnchanged && item.changeType == .unchanged)
 532                }
 533                return DomainDiffSection(title: section.title, items: items)
 534            }
 535            .filter { !$0.items.isEmpty }
 536    }
 537
 538    private var hasLowSeverityChanges: Bool {
 539        sections.flatMap(\.items).contains { $0.hasChanges && $0.severity == .low }
 540    }
 541
 542    var body: some View {
 543        VStack(alignment: .leading, spacing: 12) {
 544            HStack {
 545                SectionTitleView(title: title)
 546                Spacer()
 547                if hasLowSeverityChanges {
 548                    Button(showsLowSeverity ? "Hide Low" : "Show Low") {
 549                        showsLowSeverity.toggle()
 550                    }
 551                    .buttonStyle(.bordered)
 552                    .font(.system(.caption, design: .monospaced))
 553                }
 554            }
 555            if filteredSections.isEmpty {
 556                MessageCardView(text: "No comparison data available", isError: false)
 557            } else {
 558                ForEach(filteredSections) { section in
 559                    CardView(allowsHorizontalScroll: false) {
 560                        DisclosureGroup(isExpanded: binding(for: section)) {
 561                            let visibleItems = showsUnchanged ? section.items : section.items.filter(\.hasChanges)
 562
 563                            ForEach(visibleItems) { item in
 564                                VStack(alignment: .leading, spacing: 6) {
 565                                    HStack {
 566                                        Text(item.label)
 567                                            .font(.system(.caption, design: .monospaced))
 568                                            .foregroundStyle(.secondary)
 569                                        Spacer()
 570                                        Text("\(item.severity.title) • \(changeLabel(for: item.changeType))")
 571                                            .font(.system(.caption2, design: .monospaced))
 572                                            .foregroundStyle(changeColor(for: item))
 573                                            .padding(.horizontal, 8)
 574                                            .padding(.vertical, 4)
 575                                            .background(changeColor(for: item).opacity(0.16))
 576                                            .clipShape(Capsule())
 577                                    }
 578
 579                                    if let oldValue = item.oldValue {
 580                                        VStack(alignment: .leading, spacing: 2) {
 581                                            Text("Old")
 582                                                .font(.system(.caption2, design: .monospaced))
 583                                                .foregroundStyle(.secondary)
 584                                            Text(oldValue)
 585                                                .font(.system(.caption2, design: .monospaced))
 586                                                .foregroundStyle(.secondary)
 587                                                .textSelection(.enabled)
 588                                        }
 589                                    }
 590
 591                                    if let newValue = item.newValue {
 592                                        VStack(alignment: .leading, spacing: 2) {
 593                                            Text("New")
 594                                                .font(.system(.caption2, design: .monospaced))
 595                                                .foregroundStyle(.secondary)
 596                                            Text(newValue)
 597                                                .font(.system(.caption, design: .monospaced))
 598                                                .foregroundStyle(item.hasChanges ? .primary : .secondary)
 599                                                .textSelection(.enabled)
 600                                        }
 601                                    }
 602                                }
 603                                .padding(10)
 604                                .background(item.hasChanges ? changeColor(for: item).opacity(0.08) : Color(.systemGray6).opacity(0.25))
 605                                .cornerRadius(8)
 606                            }
 607                        } label: {
 608                            HStack {
 609                                Text(section.title)
 610                                    .font(.system(.subheadline, design: .monospaced))
 611                                    .fontWeight(.semibold)
 612                                    .foregroundStyle(sectionColor(section))
 613                                Spacer()
 614                                Text(section.severity.title)
 615                                    .font(.system(.caption2, design: .monospaced))
 616                                    .foregroundStyle(sectionColor(section))
 617                            }
 618                        }
 619                    }
 620                }
 621            }
 622        }
 623    }
 624
 625    private func changeLabel(for changeType: DiffChangeType) -> String {
 626        switch changeType {
 627        case .added:
 628            return "Added"
 629        case .removed:
 630            return "Removed"
 631        case .changed:
 632            return "Changed"
 633        case .unchanged:
 634            return "Unchanged"
 635        }
 636    }
 637
 638    private func changeColor(for item: DomainDiffItem) -> Color {
 639        if item.changeType == .unchanged {
 640            return .secondary
 641        }
 642
 643        switch item.severity {
 644        case .low:
 645            return .blue
 646        case .medium:
 647            return .yellow
 648        case .high:
 649            return .red
 650        }
 651    }
 652
 653    private func sectionColor(_ section: DomainDiffSection) -> Color {
 654        switch section.severity {
 655        case .low:
 656            return .blue
 657        case .medium:
 658            return .yellow
 659        case .high:
 660            return .red
 661        }
 662    }
 663
 664    private func binding(for section: DomainDiffSection) -> Binding<Bool> {
 665        Binding(
 666            get: { !collapsedSections.contains(section.id) },
 667            set: { isExpanded in
 668                if isExpanded {
 669                    collapsedSections.remove(section.id)
 670                } else {
 671                    collapsedSections.insert(section.id)
 672                }
 673            }
 674        )
 675    }
 676}
 677
 678struct TrackedDomainDetailHeaderView: View {
 679    let trackedDomain: TrackedDomain
 680
 681    var body: some View {
 682        VStack(alignment: .leading, spacing: 4) {
 683            if let note = trackedDomain.note?.nilIfEmpty {
 684                LabeledValueRow(row: InfoRowViewData(label: "Tracking Note", value: note, tone: .secondary))
 685            }
 686            HStack(spacing: 8) {
 687                if trackedDomain.isPinned {
 688                    Label("Pinned", systemImage: "pin.fill")
 689                }
 690                Text("Last refresh \(trackedDomain.updatedAt.formatted(date: .abbreviated, time: .shortened))")
 691            }
 692            .font(.system(.caption2, design: .monospaced))
 693            .foregroundStyle(.secondary)
 694        }
 695    }
 696}
 697
 698struct DomainSectionView: View {
 699    let rows: [InfoRowViewData]
 700    let suggestions: [DomainSuggestionViewData]
 701    let showSuggestions: Bool
 702    let availabilityLoading: Bool
 703    let suggestionsLoading: Bool
 704    let trackedDomain: TrackedDomain?
 705    let trackingLimitMessage: String?
 706    let onTrack: () -> Void
 707    let onTogglePinned: () -> Void
 708    let onEditNote: (() -> Void)?
 709
 710    var body: some View {
 711        VStack(alignment: .leading, spacing: 12) {
 712            HStack {
 713                SectionTitleView(title: "Domain")
 714                Spacer()
 715                if let trackedDomain {
 716                    HStack(spacing: 8) {
 717                        Text("Tracked")
 718                            .font(.system(.caption, design: .monospaced))
 719                            .foregroundStyle(.green)
 720                        Button {
 721                            onTogglePinned()
 722                        } label: {
 723                            Image(systemName: trackedDomain.isPinned ? "pin.fill" : "pin")
 724                        }
 725                        .buttonStyle(.bordered)
 726                        .font(.system(.caption, design: .monospaced))
 727                        if let onEditNote {
 728                            Button("Note") {
 729                                onEditNote()
 730                            }
 731                            .buttonStyle(.bordered)
 732                            .font(.system(.caption, design: .monospaced))
 733                        }
 734                    }
 735                } else {
 736                    Button("Track") {
 737                        onTrack()
 738                    }
 739                    .buttonStyle(.bordered)
 740                    .font(.system(.caption, design: .monospaced))
 741                }
 742            }
 743            CardView(allowsHorizontalScroll: false) {
 744                ForEach(rows) { row in
 745                    LabeledValueRow(row: row)
 746                }
 747                if let trackedDomain {
 748                    TrackedDomainDetailHeaderView(trackedDomain: trackedDomain)
 749                        .padding(.top, 4)
 750                } else if let trackingLimitMessage {
 751                    MessageRowView(text: trackingLimitMessage, isError: false)
 752                        .padding(.top, 4)
 753                }
 754                if availabilityLoading {
 755                    ProgressView("Checking availability…")
 756                        .appLoadingStyle()
 757                        .padding(.top, 4)
 758                }
 759                if showSuggestions {
 760                    Text("Suggestions")
 761                        .font(.system(.caption, design: .monospaced))
 762                        .foregroundStyle(.secondary)
 763                        .padding(.top, 4)
 764                    if suggestionsLoading {
 765                        ProgressView("Checking alternatives…")
 766                            .appLoadingStyle()
 767                    } else if suggestions.isEmpty {
 768                        MessageRowView(text: "No suggestions", isError: false)
 769                    } else {
 770                        ForEach(suggestions) { suggestion in
 771                            HStack {
 772                                Text(suggestion.domain)
 773                                    .font(.system(.caption, design: .monospaced))
 774                                    .foregroundStyle(.primary)
 775                                    .textSelection(.enabled)
 776                                Spacer()
 777                                Text(suggestion.status)
 778                                    .font(.system(.caption2, design: .monospaced))
 779                                    .foregroundStyle(ResultColors.color(for: suggestion.tone))
 780                            }
 781                        }
 782                    }
 783                }
 784            }
 785        }
 786    }
 787}
 788
 789struct OwnershipSectionView: View {
 790    let rows: [InfoRowViewData]
 791    let loading: Bool
 792    let error: String?
 793    let showsHistoryPlaceholder: Bool
 794
 795    var body: some View {
 796        VStack(alignment: .leading, spacing: 12) {
 797            SectionTitleView(title: "Ownership")
 798            CardView(allowsHorizontalScroll: false) {
 799                if loading {
 800                    ProgressView("Fetching RDAP ownership…")
 801                        .appLoadingStyle()
 802                } else {
 803                    ForEach(rows) { row in
 804                        LabeledValueRow(row: row)
 805                    }
 806                    if let error, rows.allSatisfy({ $0.value == "Unavailable" }) {
 807                        MessageRowView(text: error, isError: error != "Unavailable")
 808                            .padding(.top, 4)
 809                    }
 810                    if showsHistoryPlaceholder {
 811                        MessageRowView(text: "Ownership history (coming soon)", isError: false)
 812                            .padding(.top, 4)
 813                    }
 814                }
 815            }
 816        }
 817    }
 818}
 819
 820struct SubdomainsSectionView: View {
 821    let rows: [SubdomainRowViewData]
 822    let loading: Bool
 823    let error: String?
 824    let showsExtendedPlaceholder: Bool
 825
 826    var body: some View {
 827        VStack(alignment: .leading, spacing: 12) {
 828            HStack {
 829                SectionTitleView(title: "Subdomains")
 830                Spacer()
 831                Text("\(rows.count)")
 832                    .font(.system(.caption2, design: .monospaced))
 833                    .foregroundStyle(.secondary)
 834            }
 835
 836            CardView(allowsHorizontalScroll: false) {
 837                if loading {
 838                    ProgressView("Checking certificate transparency…")
 839                        .appLoadingStyle()
 840                } else if rows.isEmpty {
 841                    MessageRowView(text: error ?? "No passive subdomains found", isError: false)
 842                    if showsExtendedPlaceholder {
 843                        MessageRowView(text: "Extended subdomain discovery (Data+)", isError: false)
 844                            .padding(.top, 4)
 845                    }
 846                } else {
 847                    ForEach(rows) { row in
 848                        HStack(spacing: 8) {
 849                            Text(row.hostname)
 850                                .font(.system(.caption, design: .monospaced))
 851                                .foregroundStyle(.primary)
 852                                .textSelection(.enabled)
 853                            Spacer()
 854                            if row.isInteresting {
 855                                Text("Interesting")
 856                                    .font(.system(.caption2, design: .monospaced))
 857                                    .foregroundStyle(.yellow)
 858                                    .padding(.horizontal, 8)
 859                                    .padding(.vertical, 4)
 860                                    .background(Color.yellow.opacity(0.14))
 861                                    .clipShape(Capsule())
 862                            }
 863                        }
 864                    }
 865                    if showsExtendedPlaceholder {
 866                        MessageRowView(text: "Extended subdomain discovery (Data+)", isError: false)
 867                            .padding(.top, 4)
 868                    }
 869                }
 870            }
 871        }
 872    }
 873}
 874
 875struct DNSSectionView: View {
 876    let dnssecLabel: String?
 877    let sections: [DNSRecordSectionViewData]
 878    let ptrMessage: SectionMessageViewData?
 879    let loading: Bool
 880    let sectionError: String?
 881
 882    var body: some View {
 883        VStack(alignment: .leading, spacing: 12) {
 884            HStack(alignment: .top, spacing: 8) {
 885                SectionTitleView(title: "DNS")
 886                Spacer()
 887                if let dnssecLabel {
 888                    Text(dnssecLabel)
 889                        .font(.system(.caption2, design: .monospaced))
 890                        .foregroundStyle(.secondary)
 891                        .multilineTextAlignment(.trailing)
 892                }
 893            }
 894
 895            if loading {
 896                LoadingCardView(text: "Querying DNS…")
 897            } else if let sectionError, sections.isEmpty {
 898                MessageCardView(text: sectionError, isError: true)
 899            } else {
 900                ForEach(sections) { section in
 901                    CardView {
 902                        Text(section.title)
 903                            .font(.system(.subheadline, design: .monospaced))
 904                            .fontWeight(.semibold)
 905                            .foregroundStyle(.cyan)
 906
 907                        if let message = section.message {
 908                            MessageRowView(text: message.text, isError: message.isError)
 909                        }
 910
 911                        ForEach(section.rows) { row in
 912                            LabeledValueRow(row: row)
 913                        }
 914
 915                        if let wildcardTitle = section.wildcardTitle {
 916                            Text(wildcardTitle)
 917                                .font(.system(.caption, design: .monospaced))
 918                                .foregroundStyle(.secondary)
 919                                .padding(.top, 4)
 920                            ForEach(section.wildcardRows) { row in
 921                                LabeledValueRow(row: row)
 922                            }
 923                        }
 924                    }
 925                }
 926
 927                if let ptrMessage {
 928                    CardView {
 929                        Text("PTR")
 930                            .font(.system(.subheadline, design: .monospaced))
 931                            .fontWeight(.semibold)
 932                            .foregroundStyle(.cyan)
 933                        MessageRowView(text: ptrMessage.text, isError: ptrMessage.isError)
 934                    }
 935                }
 936            }
 937        }
 938    }
 939}
 940
 941struct WebSectionView: View {
 942    let certificateRows: [InfoRowViewData]
 943    let sslInfo: SSLCertificateInfo?
 944    let sslLoading: Bool
 945    let sslError: String?
 946    let responseRows: [InfoRowViewData]
 947    let headers: [HTTPHeader]
 948    let headersLoading: Bool
 949    let headersError: String?
 950    let redirects: [RedirectHopViewData]
 951    let redirectLoading: Bool
 952    let redirectError: String?
 953    let finalURL: String?
 954
 955    var body: some View {
 956        VStack(alignment: .leading, spacing: 12) {
 957            SectionTitleView(title: "Web")
 958
 959            CardView {
 960                Text("TLS")
 961                    .font(.system(.subheadline, design: .monospaced))
 962                    .fontWeight(.semibold)
 963                    .foregroundStyle(.cyan)
 964                if sslLoading {
 965                    ProgressView("Checking certificate…")
 966                        .appLoadingStyle()
 967                } else if let sslError {
 968                    MessageRowView(text: sslError, isError: true)
 969                } else {
 970                    ForEach(certificateRows) { row in
 971                        LabeledValueRow(row: row)
 972                    }
 973                    if let sslInfo, !sslInfo.subjectAltNames.isEmpty {
 974                        Text("SANs")
 975                            .font(.system(.caption2, design: .monospaced))
 976                            .foregroundStyle(.secondary)
 977                        ForEach(sslInfo.subjectAltNames, id: \.self) { san in
 978                            Text(san)
 979                                .font(.system(.caption, design: .monospaced))
 980                                .textSelection(.enabled)
 981                        }
 982                    }
 983                }
 984            }
 985
 986            CardView {
 987                Text("Headers")
 988                    .font(.system(.subheadline, design: .monospaced))
 989                    .fontWeight(.semibold)
 990                    .foregroundStyle(.cyan)
 991                if headersLoading {
 992                    ProgressView("Fetching headers…")
 993                        .appLoadingStyle()
 994                } else if let headersError {
 995                    MessageRowView(text: headersError, isError: true)
 996                } else {
 997                    ForEach(responseRows) { row in
 998                        LabeledValueRow(row: row)
 999                    }
1000                    if headers.isEmpty {
1001                        MessageRowView(text: "No HTTP headers returned", isError: false)
1002                    } else {
1003                        ForEach(headers) { header in
1004                            HStack(alignment: .top, spacing: 4) {
1005                                Text(header.name + ":")
1006                                    .font(.system(.caption, design: .monospaced))
1007                                    .foregroundStyle(header.isSecurityHeader ? .yellow : .cyan)
1008                                Text(header.value)
1009                                    .font(.system(.caption, design: .monospaced))
1010                                    .foregroundStyle(.primary)
1011                                    .textSelection(.enabled)
1012                            }
1013                        }
1014                    }
1015                }
1016            }
1017
1018            CardView {
1019                Text("Redirects")
1020                    .font(.system(.subheadline, design: .monospaced))
1021                    .fontWeight(.semibold)
1022                    .foregroundStyle(.cyan)
1023                if redirectLoading {
1024                    ProgressView("Tracing redirects…")
1025                        .appLoadingStyle()
1026                } else if let redirectError {
1027                    MessageRowView(text: redirectError, isError: true)
1028                } else if redirects.isEmpty {
1029                    MessageRowView(text: "No redirect data available", isError: false)
1030                } else {
1031                    if let finalURL {
1032                        LabeledValueRow(row: InfoRowViewData(label: "Final URL", value: finalURL, tone: .secondary))
1033                    }
1034                    ForEach(redirects) { redirect in
1035                        HStack(alignment: .top, spacing: 6) {
1036                            Text(redirect.stepLabel)
1037                                .font(.system(.caption, design: .monospaced))
1038                                .foregroundStyle(.secondary)
1039                                .frame(width: 16, alignment: .trailing)
1040                            Text(redirect.statusCode)
1041                                .font(.system(.caption, design: .monospaced))
1042                                .foregroundStyle(.cyan)
1043                                .frame(width: 36, alignment: .leading)
1044                            Text(redirect.url)
1045                                .font(.system(.caption, design: .monospaced))
1046                                .textSelection(.enabled)
1047                            if redirect.isFinal {
1048                                Text("(final)")
1049                                    .font(.system(.caption2, design: .monospaced))
1050                                    .foregroundStyle(.secondary)
1051                            }
1052                        }
1053                    }
1054                }
1055            }
1056        }
1057    }
1058}
1059
1060struct EmailSectionView: View {
1061    let rows: [EmailRowViewData]
1062    let loading: Bool
1063    let error: String?
1064
1065    var body: some View {
1066        VStack(alignment: .leading, spacing: 12) {
1067            SectionTitleView(title: "Email")
1068            CardView {
1069                if loading {
1070                    ProgressView("Checking email records…")
1071                        .appLoadingStyle()
1072                } else if let error {
1073                    MessageRowView(text: error, isError: true)
1074                } else if rows.isEmpty {
1075                    MessageRowView(text: "No email security records found", isError: false)
1076                } else {
1077                    ForEach(rows) { row in
1078                        VStack(alignment: .leading, spacing: 4) {
1079                            HStack(spacing: 8) {
1080                                Text(row.label)
1081                                    .font(.system(.caption, design: .monospaced))
1082                                    .foregroundStyle(.cyan)
1083                                    .frame(width: 76, alignment: .leading)
1084                                Text(row.status)
1085                                    .font(.system(.caption, design: .monospaced))
1086                                    .foregroundStyle(ResultColors.color(for: row.statusTone))
1087                            }
1088                            Text(row.detail)
1089                                .font(.system(.caption2, design: .monospaced))
1090                                .foregroundStyle(.primary)
1091                                .textSelection(.enabled)
1092                            if let auxiliaryDetail = row.auxiliaryDetail {
1093                                Text(auxiliaryDetail)
1094                                    .font(.system(.caption2, design: .monospaced))
1095                                    .foregroundStyle(.secondary)
1096                            }
1097                        }
1098                    }
1099                }
1100            }
1101        }
1102    }
1103}
1104
1105struct NetworkSectionView: View {
1106    let reachabilityRows: [ReachabilityRowViewData]
1107    let reachabilityLoading: Bool
1108    let reachabilityError: String?
1109    let locationRows: [InfoRowViewData]
1110    let geolocation: IPGeolocation?
1111    let geolocationLoading: Bool
1112    let geolocationError: String?
1113    let standardPortRows: [PortScanRowViewData]
1114    let customPortRows: [PortScanRowViewData]
1115    let portScanLoading: Bool
1116    let portScanError: String?
1117    let customPortScanLoading: Bool
1118    let customPortScanError: String?
1119    let isCloudflareProxied: Bool
1120    @Binding var customPortsExpanded: Bool
1121    @Binding var customPortInput: String
1122    let onScanCustomPorts: () -> Void
1123
1124    var body: some View {
1125        VStack(alignment: .leading, spacing: 12) {
1126            SectionTitleView(title: "Network")
1127
1128            CardView {
1129                Text("Reachability")
1130                    .font(.system(.subheadline, design: .monospaced))
1131                    .fontWeight(.semibold)
1132                    .foregroundStyle(.cyan)
1133                if reachabilityLoading {
1134                    ProgressView("Checking ports…")
1135                        .appLoadingStyle()
1136                } else if let reachabilityError {
1137                    MessageRowView(text: reachabilityError, isError: true)
1138                } else {
1139                    ForEach(reachabilityRows) { row in
1140                        HStack {
1141                            Text(row.portLabel)
1142                                .font(.system(.caption, design: .monospaced))
1143                            Spacer()
1144                            Text(row.latencyLabel)
1145                                .font(.system(.caption2, design: .monospaced))
1146                                .foregroundStyle(.secondary)
1147                            Text(row.statusLabel)
1148                                .font(.system(.caption, design: .monospaced))
1149                                .foregroundStyle(ResultColors.color(for: row.statusTone))
1150                        }
1151                    }
1152                }
1153            }
1154
1155            CardView(allowsHorizontalScroll: false) {
1156                Text("Location")
1157                    .font(.system(.subheadline, design: .monospaced))
1158                    .fontWeight(.semibold)
1159                    .foregroundStyle(.cyan)
1160                if geolocationLoading {
1161                    ProgressView("Looking up location…")
1162                        .appLoadingStyle()
1163                } else if let geolocationError, geolocation == nil {
1164                    MessageRowView(text: geolocationError, isError: geolocationError != "No A record available")
1165                } else if let geolocation {
1166                    ForEach(locationRows) { row in
1167                        LabeledValueRow(row: row)
1168                    }
1169                    if let latitude = geolocation.latitude, let longitude = geolocation.longitude {
1170                        let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
1171                        Map(initialPosition: .region(MKCoordinateRegion(
1172                            center: coordinate,
1173                            span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1)
1174                        ))) {
1175                            Marker(geolocation.ip, coordinate: coordinate)
1176                        }
1177                        .mapStyle(.standard)
1178                        .frame(maxWidth: .infinity)
1179                        .frame(height: 180)
1180                        .cornerRadius(8)
1181                    }
1182                } else {
1183                    MessageRowView(text: "No location data available", isError: false)
1184                }
1185            }
1186
1187            CardView(allowsHorizontalScroll: false) {
1188                Text("Port Scan")
1189                    .font(.system(.subheadline, design: .monospaced))
1190                    .fontWeight(.semibold)
1191                    .foregroundStyle(.cyan)
1192
1193                if isCloudflareProxied {
1194                    Text("Domain is behind Cloudflare's proxy. Results reflect the edge, not the origin.")
1195                        .font(.system(.caption2, design: .monospaced))
1196                        .foregroundStyle(.orange)
1197                        .fixedSize(horizontal: false, vertical: true)
1198                }
1199
1200                if portScanLoading {
1201                    ProgressView("Scanning ports…")
1202                        .appLoadingStyle()
1203                } else if let portScanError, standardPortRows.isEmpty {
1204                    MessageRowView(text: portScanError, isError: true)
1205                } else {
1206                    Text("Standard Ports")
1207                        .font(.system(.caption, design: .monospaced))
1208                        .foregroundStyle(.secondary)
1209                    PortRowsView(rows: standardPortRows)
1210                }
1211
1212                DisclosureGroup("Custom Ports", isExpanded: $customPortsExpanded) {
1213                    VStack(alignment: .leading, spacing: 10) {
1214                        TextField("8888, 9000, 27017", text: $customPortInput)
1215                            .font(.system(.caption, design: .monospaced))
1216                            .textInputAutocapitalization(.never)
1217                            .autocorrectionDisabled()
1218                            .keyboardType(.numberPad)
1219                            .padding(10)
1220                            .background(Color(.systemGray6).opacity(0.5))
1221                            .cornerRadius(6)
1222
1223                        Button("Scan") {
1224                            onScanCustomPorts()
1225                        }
1226                        .buttonStyle(.borderedProminent)
1227                        .disabled(customPortScanLoading)
1228
1229                        if customPortScanLoading {
1230                            ProgressView("Scanning custom ports…")
1231                                .appLoadingStyle()
1232                        } else if let customPortScanError {
1233                            MessageRowView(text: customPortScanError, isError: true)
1234                        } else {
1235                            PortRowsView(rows: customPortRows)
1236                        }
1237                    }
1238                    .padding(.top, 8)
1239                }
1240                .font(.system(.caption, design: .monospaced))
1241                .tint(.secondary)
1242            }
1243        }
1244    }
1245}
1246
1247struct PortRowsView: View {
1248    let rows: [PortScanRowViewData]
1249
1250    var body: some View {
1251        if rows.isEmpty {
1252            MessageRowView(text: "No results", isError: false)
1253        } else {
1254            ForEach(rows) { row in
1255                VStack(alignment: .leading, spacing: 2) {
1256                    HStack {
1257                        Text(row.portLabel)
1258                            .font(.system(.caption, design: .monospaced))
1259                            .frame(width: 52, alignment: .leading)
1260                        Text(row.service)
1261                            .font(.system(.caption, design: .monospaced))
1262                            .foregroundStyle(.primary)
1263                        Spacer()
1264                        if let durationLabel = row.durationLabel {
1265                            Text(durationLabel)
1266                                .font(.system(.caption2, design: .monospaced))
1267                                .foregroundStyle(.secondary)
1268                        }
1269                        Text(row.statusLabel)
1270                            .font(.system(.caption2, design: .monospaced))
1271                            .foregroundStyle(ResultColors.color(for: row.statusTone))
1272                    }
1273                    if let banner = row.banner {
1274                        Text(banner)
1275                            .font(.system(.caption2, design: .monospaced))
1276                            .foregroundStyle(.secondary)
1277                            .padding(.leading, 8)
1278                    }
1279                }
1280            }
1281        }
1282    }
1283}
1284
1285struct SectionTitleView: View {
1286    let title: String
1287
1288    var body: some View {
1289        Text(title)
1290            .font(.system(.headline))
1291            .foregroundStyle(.white)
1292    }
1293}
1294
1295struct CardView<Content: View>: View {
1296    let allowsHorizontalScroll: Bool
1297    let content: Content
1298
1299    init(allowsHorizontalScroll: Bool = true, @ViewBuilder content: () -> Content) {
1300        self.allowsHorizontalScroll = allowsHorizontalScroll
1301        self.content = content()
1302    }
1303
1304    var body: some View {
1305        Group {
1306            if allowsHorizontalScroll {
1307                ScrollView(.horizontal) {
1308                    cardContent
1309                        .scrollTargetLayout()
1310                }
1311                .scrollBounceBehavior(.basedOnSize, axes: .horizontal)
1312            } else {
1313                cardContent
1314                    .frame(maxWidth: .infinity, alignment: .leading)
1315            }
1316        }
1317        .frame(maxWidth: .infinity, alignment: .leading)
1318        .padding(10)
1319        .background(Color(.systemGray6).opacity(0.5))
1320        .cornerRadius(6)
1321    }
1322
1323    private var cardContent: some View {
1324        VStack(alignment: .leading, spacing: 6) {
1325            content
1326        }
1327    }
1328}
1329
1330struct LoadingCardView: View {
1331    let text: String
1332
1333    var body: some View {
1334        CardView {
1335            ProgressView(text)
1336                .appLoadingStyle()
1337                .frame(maxWidth: .infinity, alignment: .center)
1338        }
1339    }
1340}
1341
1342struct MessageCardView: View {
1343    let text: String
1344    let isError: Bool
1345
1346    var body: some View {
1347        CardView {
1348            MessageRowView(text: text, isError: isError)
1349        }
1350    }
1351}
1352
1353struct MessageRowView: View {
1354    let text: String
1355    let isError: Bool
1356
1357    var body: some View {
1358        Label(text, systemImage: isError ? "exclamationmark.triangle.fill" : "info.circle")
1359            .font(.system(.caption, design: .monospaced))
1360            .foregroundStyle(isError ? .red : .secondary)
1361    }
1362}
1363
1364struct LabeledValueRow: View {
1365    let row: InfoRowViewData
1366
1367    var body: some View {
1368        VStack(alignment: .leading, spacing: 2) {
1369            Text(row.label)
1370                .font(.system(.caption2, design: .monospaced))
1371                .foregroundStyle(.secondary)
1372            Text(row.value)
1373                .font(.system(.caption, design: .monospaced))
1374                .foregroundStyle(ResultColors.color(for: row.tone))
1375                .textSelection(.enabled)
1376        }
1377    }
1378}
1379
1380enum ResultColors {
1381    static func color(for tone: ResultTone) -> Color {
1382        switch tone {
1383        case .primary:
1384            return .primary
1385        case .secondary:
1386            return .secondary
1387        case .success:
1388            return .green
1389        case .warning:
1390            return .yellow
1391        case .failure:
1392            return .red
1393        }
1394    }
1395}
1396
1397extension DateFormatter {
1398    static let certDate: DateFormatter = {
1399        let formatter = DateFormatter()
1400        formatter.dateStyle = .medium
1401        formatter.timeStyle = .short
1402        return formatter
1403    }()
1404}
1405
1406private extension View {
1407    func appLoadingStyle() -> some View {
1408        font(.system(.caption, design: .monospaced))
1409    }
1410}
1411
1412private extension String {
1413    var nilIfEmpty: String? {
1414        isEmpty ? nil : self
1415    }
1416}
1417
1418private struct SettingsView: View {
1419    @AppStorage(DNSResolverOption.userDefaultsKey)
1420    private var storedResolverURL = DNSResolverOption.defaultURLString
1421
1422    @State private var resolverOption: DNSResolverOption = .cloudflare
1423    @State private var customResolverURL = DNSResolverOption.defaultURLString
1424
1425    private var customResolverError: String? {
1426        guard resolverOption == .custom else {
1427            return nil
1428        }
1429        return DNSResolverOption.isValidCustomURL(customResolverURL) ? nil : "Resolver URL must start with https://"
1430    }
1431
1432    var body: some View {
1433        Form {
1434            Section {
1435                Picker("Resolver", selection: $resolverOption) {
1436                    ForEach(DNSResolverOption.allCases) { option in
1437                        Text(option.title).tag(option)
1438                    }
1439                }
1440
1441                if resolverOption == .custom {
1442                    TextField("https://resolver.example/dns-query", text: $customResolverURL)
1443                        .textInputAutocapitalization(.never)
1444                        .autocorrectionDisabled()
1445                        .keyboardType(.URL)
1446
1447                    if let customResolverError {
1448                        Text(customResolverError)
1449                            .font(.caption)
1450                            .foregroundStyle(.red)
1451                    }
1452                }
1453            }
1454        }
1455        .navigationTitle("Settings")
1456        .onAppear {
1457            let currentResolverURL = storedResolverURL.trimmingCharacters(in: .whitespacesAndNewlines)
1458            resolverOption = DNSResolverOption.option(for: currentResolverURL)
1459            customResolverURL = resolverOption == .custom ? currentResolverURL : DNSResolverOption.defaultURLString
1460        }
1461        .onChange(of: resolverOption) { _, newValue in
1462            guard let presetURL = newValue.urlString else {
1463                storedResolverURL = customResolverURL.trimmingCharacters(in: .whitespacesAndNewlines)
1464                return
1465            }
1466            storedResolverURL = presetURL
1467        }
1468        .onChange(of: customResolverURL) { _, newValue in
1469            guard resolverOption == .custom else { return }
1470            storedResolverURL = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
1471        }
1472    }
1473}
1474
1475#Preview {
1476    ContentView()
1477}