DomainDig/ContentView.swift

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

1501 lines · 60600 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(format: .text)
 308                    }
 309                    Button("Export CSV") {
 310                        shareSingleResults(format: .csv)
 311                    }
 312                    Button("Export JSON") {
 313                        shareSingleResults(format: .json)
 314                    }
 315                } label: {
 316                    Image(systemName: "square.and.arrow.up")
 317                        .font(.system(.body))
 318                        .foregroundStyle(.secondary)
 319                }
 320            }
 321        }
 322    }
 323
 324    private var batchSection: some View {
 325        VStack(alignment: .leading, spacing: 12) {
 326            HStack {
 327                Spacer()
 328                if viewModel.batchLookupRunning {
 329                    Button("Cancel") {
 330                        viewModel.cancelBatchLookup()
 331                    }
 332                    .buttonStyle(.bordered)
 333                    .font(.system(.caption, design: .monospaced))
 334                }
 335                if !viewModel.currentBatchResultEntries.isEmpty {
 336                    Menu {
 337                        Button("Export Batch TXT") {
 338                            shareBatchResults(format: .text)
 339                        }
 340                        Button("Export Batch CSV") {
 341                            shareBatchResults(format: .csv)
 342                        }
 343                        Button("Export Batch JSON") {
 344                            shareBatchResults(format: .json)
 345                        }
 346                    } label: {
 347                        Label("Export", systemImage: "square.and.arrow.up")
 348                            .font(.system(.caption, design: .monospaced))
 349                    }
 350                    .buttonStyle(.bordered)
 351                }
 352            }
 353
 354            BatchResultsView(
 355                viewModel: viewModel,
 356                title: viewModel.batchLookupSource == .watchlistRefresh ? "Tracked Domain Refresh" : "Batch Results"
 357            )
 358        }
 359    }
 360
 361    private var recentSearchesSection: some View {
 362        VStack(alignment: .leading, spacing: 8) {
 363            HStack {
 364                Text("RECENT")
 365                    .font(.system(.caption2, design: .monospaced))
 366                    .foregroundStyle(.secondary)
 367                Spacer()
 368                Button("Clear") {
 369                    viewModel.clearRecentSearches()
 370                }
 371                .font(.system(.caption2, design: .monospaced))
 372                .foregroundStyle(.secondary)
 373            }
 374
 375            ForEach(viewModel.recentSearches, id: \.self) { domain in
 376                Button {
 377                    viewModel.domain = domain
 378                    domainFieldFocused = false
 379                    viewModel.run()
 380                } label: {
 381                    Text(domain)
 382                        .font(.system(.callout, design: .monospaced))
 383                        .foregroundStyle(.primary)
 384                        .frame(maxWidth: .infinity, alignment: .leading)
 385                        .padding(.vertical, 6)
 386                        .padding(.horizontal, 10)
 387                        .background(Color(.systemGray6).opacity(0.5))
 388                        .cornerRadius(6)
 389                }
 390            }
 391        }
 392        .padding(.top, 8)
 393    }
 394
 395    private func runCustomPortScan() {
 396        let ports = parsedCustomPorts(from: customPortInput)
 397        Task {
 398            await viewModel.runCustomPortScan(ports: ports)
 399        }
 400    }
 401
 402    private func parsedCustomPorts(from input: String) -> [UInt16] {
 403        let parts = input.split(separator: ",", omittingEmptySubsequences: true)
 404        var seen = Set<UInt16>()
 405        var ports: [UInt16] = []
 406
 407        for part in parts {
 408            let trimmed = part.trimmingCharacters(in: .whitespacesAndNewlines)
 409            guard let value = UInt16(trimmed), seen.insert(value).inserted else {
 410                continue
 411            }
 412            ports.append(value)
 413            if ports.count == 20 {
 414                break
 415            }
 416        }
 417
 418        return ports
 419    }
 420
 421    private func shareSingleResults(format: DomainExportFormat) {
 422        let (filename, data) = exportPayload(
 423            prefix: "domaindig_single",
 424            format: format,
 425            text: viewModel.exportText(),
 426            csv: viewModel.exportCSV(),
 427            json: viewModel.exportJSONData()
 428        )
 429        ExportPresenter.share(filename: filename, data: data)
 430    }
 431
 432    private func shareBatchResults(format: DomainExportFormat) {
 433        let (filename, data) = exportPayload(
 434            prefix: "domaindig_batch",
 435            format: format,
 436            text: viewModel.exportBatchText(),
 437            csv: viewModel.exportBatchCSV(),
 438            json: viewModel.exportBatchJSONData()
 439        )
 440        ExportPresenter.share(filename: filename, data: data)
 441    }
 442
 443    private func exportPayload(
 444        prefix: String,
 445        format: DomainExportFormat,
 446        text: String,
 447        csv: String,
 448        json: Data?
 449    ) -> (String, Data) {
 450        let formatter = DateFormatter()
 451        formatter.dateFormat = "yyyyMMdd_HHmmss"
 452        let timestamp = formatter.string(from: Date())
 453        let filename = "\(timestamp)_\(prefix).\(format.fileExtension)"
 454        let data: Data
 455
 456        switch format {
 457        case .text:
 458            data = Data(text.utf8)
 459        case .csv:
 460            data = Data(csv.utf8)
 461        case .json:
 462            data = json ?? Data("[]".utf8)
 463        }
 464
 465        return (filename, data)
 466    }
 467}
 468
 469struct SummaryView: View {
 470    let fields: [SummaryFieldViewData]
 471
 472    var body: some View {
 473        VStack(alignment: .leading, spacing: 12) {
 474            SectionTitleView(title: "Summary")
 475            LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 8) {
 476                ForEach(fields) { field in
 477                    VStack(alignment: .leading, spacing: 4) {
 478                        Text(field.label)
 479                            .font(.system(.caption2, design: .monospaced))
 480                            .foregroundStyle(.secondary)
 481                        Text(field.value)
 482                            .font(.system(.caption, design: .monospaced))
 483                            .foregroundStyle(ResultColors.color(for: field.tone))
 484                            .lineLimit(2)
 485                            .textSelection(.enabled)
 486                    }
 487                    .frame(maxWidth: .infinity, alignment: .leading)
 488                    .padding(10)
 489                    .background(Color(.systemGray6).opacity(0.5))
 490                    .cornerRadius(6)
 491                }
 492            }
 493        }
 494    }
 495}
 496
 497struct DomainChangeSummaryView: View {
 498    let summary: DomainChangeSummary
 499
 500    var body: some View {
 501        CardView(allowsHorizontalScroll: false) {
 502            HStack {
 503                Label(summary.hasChanges ? "Changed" : "Stable", systemImage: summary.hasChanges ? "arrow.triangle.2.circlepath" : "checkmark.circle")
 504                    .font(.system(.caption, design: .monospaced))
 505                    .foregroundStyle(summary.hasChanges ? severityColor(summary.severity) : .green)
 506                Spacer()
 507                Text(summary.severity.title.uppercased())
 508                    .font(.system(.caption2, design: .monospaced))
 509                    .foregroundStyle(summary.hasChanges ? severityColor(summary.severity) : .secondary)
 510                    .padding(.horizontal, 8)
 511                    .padding(.vertical, 4)
 512                    .background((summary.hasChanges ? severityColor(summary.severity) : .secondary).opacity(0.16))
 513                    .clipShape(Capsule())
 514                Text(summary.generatedAt, style: .time)
 515                    .font(.system(.caption2, design: .monospaced))
 516                    .foregroundStyle(.secondary)
 517            }
 518
 519            Text(summary.message)
 520                .font(.system(.caption, design: .monospaced))
 521                .foregroundStyle(.primary)
 522        }
 523    }
 524
 525    private func severityColor(_ severity: ChangeSeverity) -> Color {
 526        switch severity {
 527        case .low:
 528            return .secondary
 529        case .medium:
 530            return .yellow
 531        case .high:
 532            return .red
 533        }
 534    }
 535}
 536
 537struct DomainDiffView: View {
 538    let title: String
 539    let sections: [DomainDiffSection]
 540    let showsUnchanged: Bool
 541
 542    @State private var collapsedSections = Set<UUID>()
 543    @State private var showsLowSeverity = false
 544
 545    private var filteredSections: [DomainDiffSection] {
 546        sections
 547            .map { section in
 548                let items = section.items.filter { item in
 549                    if !showsUnchanged, !item.hasChanges {
 550                        return false
 551                    }
 552                    if showsLowSeverity {
 553                        return true
 554                    }
 555                    return item.severity >= .medium || (showsUnchanged && item.changeType == .unchanged)
 556                }
 557                return DomainDiffSection(title: section.title, items: items)
 558            }
 559            .filter { !$0.items.isEmpty }
 560    }
 561
 562    private var hasLowSeverityChanges: Bool {
 563        sections.flatMap(\.items).contains { $0.hasChanges && $0.severity == .low }
 564    }
 565
 566    var body: some View {
 567        VStack(alignment: .leading, spacing: 12) {
 568            HStack {
 569                SectionTitleView(title: title)
 570                Spacer()
 571                if hasLowSeverityChanges {
 572                    Button(showsLowSeverity ? "Hide Low" : "Show Low") {
 573                        showsLowSeverity.toggle()
 574                    }
 575                    .buttonStyle(.bordered)
 576                    .font(.system(.caption, design: .monospaced))
 577                }
 578            }
 579            if filteredSections.isEmpty {
 580                MessageCardView(text: "No comparison data available", isError: false)
 581            } else {
 582                ForEach(filteredSections) { section in
 583                    CardView(allowsHorizontalScroll: false) {
 584                        DisclosureGroup(isExpanded: binding(for: section)) {
 585                            let visibleItems = showsUnchanged ? section.items : section.items.filter(\.hasChanges)
 586
 587                            ForEach(visibleItems) { item in
 588                                VStack(alignment: .leading, spacing: 6) {
 589                                    HStack {
 590                                        Text(item.label)
 591                                            .font(.system(.caption, design: .monospaced))
 592                                            .foregroundStyle(.secondary)
 593                                        Spacer()
 594                                        Text("\(item.severity.title) • \(changeLabel(for: item.changeType))")
 595                                            .font(.system(.caption2, design: .monospaced))
 596                                            .foregroundStyle(changeColor(for: item))
 597                                            .padding(.horizontal, 8)
 598                                            .padding(.vertical, 4)
 599                                            .background(changeColor(for: item).opacity(0.16))
 600                                            .clipShape(Capsule())
 601                                    }
 602
 603                                    if let oldValue = item.oldValue {
 604                                        VStack(alignment: .leading, spacing: 2) {
 605                                            Text("Old")
 606                                                .font(.system(.caption2, design: .monospaced))
 607                                                .foregroundStyle(.secondary)
 608                                            Text(oldValue)
 609                                                .font(.system(.caption2, design: .monospaced))
 610                                                .foregroundStyle(.secondary)
 611                                                .textSelection(.enabled)
 612                                        }
 613                                    }
 614
 615                                    if let newValue = item.newValue {
 616                                        VStack(alignment: .leading, spacing: 2) {
 617                                            Text("New")
 618                                                .font(.system(.caption2, design: .monospaced))
 619                                                .foregroundStyle(.secondary)
 620                                            Text(newValue)
 621                                                .font(.system(.caption, design: .monospaced))
 622                                                .foregroundStyle(item.hasChanges ? .primary : .secondary)
 623                                                .textSelection(.enabled)
 624                                        }
 625                                    }
 626                                }
 627                                .padding(10)
 628                                .background(item.hasChanges ? changeColor(for: item).opacity(0.08) : Color(.systemGray6).opacity(0.25))
 629                                .cornerRadius(8)
 630                            }
 631                        } label: {
 632                            HStack {
 633                                Text(section.title)
 634                                    .font(.system(.subheadline, design: .monospaced))
 635                                    .fontWeight(.semibold)
 636                                    .foregroundStyle(sectionColor(section))
 637                                Spacer()
 638                                Text(section.severity.title)
 639                                    .font(.system(.caption2, design: .monospaced))
 640                                    .foregroundStyle(sectionColor(section))
 641                            }
 642                        }
 643                    }
 644                }
 645            }
 646        }
 647    }
 648
 649    private func changeLabel(for changeType: DiffChangeType) -> String {
 650        switch changeType {
 651        case .added:
 652            return "Added"
 653        case .removed:
 654            return "Removed"
 655        case .changed:
 656            return "Changed"
 657        case .unchanged:
 658            return "Unchanged"
 659        }
 660    }
 661
 662    private func changeColor(for item: DomainDiffItem) -> Color {
 663        if item.changeType == .unchanged {
 664            return .secondary
 665        }
 666
 667        switch item.severity {
 668        case .low:
 669            return .blue
 670        case .medium:
 671            return .yellow
 672        case .high:
 673            return .red
 674        }
 675    }
 676
 677    private func sectionColor(_ section: DomainDiffSection) -> Color {
 678        switch section.severity {
 679        case .low:
 680            return .blue
 681        case .medium:
 682            return .yellow
 683        case .high:
 684            return .red
 685        }
 686    }
 687
 688    private func binding(for section: DomainDiffSection) -> Binding<Bool> {
 689        Binding(
 690            get: { !collapsedSections.contains(section.id) },
 691            set: { isExpanded in
 692                if isExpanded {
 693                    collapsedSections.remove(section.id)
 694                } else {
 695                    collapsedSections.insert(section.id)
 696                }
 697            }
 698        )
 699    }
 700}
 701
 702struct TrackedDomainDetailHeaderView: View {
 703    let trackedDomain: TrackedDomain
 704
 705    var body: some View {
 706        VStack(alignment: .leading, spacing: 4) {
 707            if let note = trackedDomain.note?.nilIfEmpty {
 708                LabeledValueRow(row: InfoRowViewData(label: "Tracking Note", value: note, tone: .secondary))
 709            }
 710            HStack(spacing: 8) {
 711                if trackedDomain.isPinned {
 712                    Label("Pinned", systemImage: "pin.fill")
 713                }
 714                Text("Last refresh \(trackedDomain.updatedAt.formatted(date: .abbreviated, time: .shortened))")
 715            }
 716            .font(.system(.caption2, design: .monospaced))
 717            .foregroundStyle(.secondary)
 718        }
 719    }
 720}
 721
 722struct DomainSectionView: View {
 723    let rows: [InfoRowViewData]
 724    let suggestions: [DomainSuggestionViewData]
 725    let showSuggestions: Bool
 726    let availabilityLoading: Bool
 727    let suggestionsLoading: Bool
 728    let trackedDomain: TrackedDomain?
 729    let trackingLimitMessage: String?
 730    let onTrack: () -> Void
 731    let onTogglePinned: () -> Void
 732    let onEditNote: (() -> Void)?
 733
 734    var body: some View {
 735        VStack(alignment: .leading, spacing: 12) {
 736            HStack {
 737                SectionTitleView(title: "Domain")
 738                Spacer()
 739                if let trackedDomain {
 740                    HStack(spacing: 8) {
 741                        Text("Tracked")
 742                            .font(.system(.caption, design: .monospaced))
 743                            .foregroundStyle(.green)
 744                        Button {
 745                            onTogglePinned()
 746                        } label: {
 747                            Image(systemName: trackedDomain.isPinned ? "pin.fill" : "pin")
 748                        }
 749                        .buttonStyle(.bordered)
 750                        .font(.system(.caption, design: .monospaced))
 751                        if let onEditNote {
 752                            Button("Note") {
 753                                onEditNote()
 754                            }
 755                            .buttonStyle(.bordered)
 756                            .font(.system(.caption, design: .monospaced))
 757                        }
 758                    }
 759                } else {
 760                    Button("Track") {
 761                        onTrack()
 762                    }
 763                    .buttonStyle(.bordered)
 764                    .font(.system(.caption, design: .monospaced))
 765                }
 766            }
 767            CardView(allowsHorizontalScroll: false) {
 768                ForEach(rows) { row in
 769                    LabeledValueRow(row: row)
 770                }
 771                if let trackedDomain {
 772                    TrackedDomainDetailHeaderView(trackedDomain: trackedDomain)
 773                        .padding(.top, 4)
 774                } else if let trackingLimitMessage {
 775                    MessageRowView(text: trackingLimitMessage, isError: false)
 776                        .padding(.top, 4)
 777                }
 778                if availabilityLoading {
 779                    ProgressView("Checking availability…")
 780                        .appLoadingStyle()
 781                        .padding(.top, 4)
 782                }
 783                if showSuggestions {
 784                    Text("Suggestions")
 785                        .font(.system(.caption, design: .monospaced))
 786                        .foregroundStyle(.secondary)
 787                        .padding(.top, 4)
 788                    if suggestionsLoading {
 789                        ProgressView("Checking alternatives…")
 790                            .appLoadingStyle()
 791                    } else if suggestions.isEmpty {
 792                        MessageRowView(text: "No suggestions", isError: false)
 793                    } else {
 794                        ForEach(suggestions) { suggestion in
 795                            HStack {
 796                                Text(suggestion.domain)
 797                                    .font(.system(.caption, design: .monospaced))
 798                                    .foregroundStyle(.primary)
 799                                    .textSelection(.enabled)
 800                                Spacer()
 801                                Text(suggestion.status)
 802                                    .font(.system(.caption2, design: .monospaced))
 803                                    .foregroundStyle(ResultColors.color(for: suggestion.tone))
 804                            }
 805                        }
 806                    }
 807                }
 808            }
 809        }
 810    }
 811}
 812
 813struct OwnershipSectionView: View {
 814    let rows: [InfoRowViewData]
 815    let loading: Bool
 816    let error: String?
 817    let showsHistoryPlaceholder: Bool
 818
 819    var body: some View {
 820        VStack(alignment: .leading, spacing: 12) {
 821            SectionTitleView(title: "Ownership")
 822            CardView(allowsHorizontalScroll: false) {
 823                if loading {
 824                    ProgressView("Fetching RDAP ownership…")
 825                        .appLoadingStyle()
 826                } else {
 827                    ForEach(rows) { row in
 828                        LabeledValueRow(row: row)
 829                    }
 830                    if let error, rows.allSatisfy({ $0.value == "Unavailable" }) {
 831                        MessageRowView(text: error, isError: error != "Unavailable")
 832                            .padding(.top, 4)
 833                    }
 834                    if showsHistoryPlaceholder {
 835                        MessageRowView(text: "Ownership history (coming soon)", isError: false)
 836                            .padding(.top, 4)
 837                    }
 838                }
 839            }
 840        }
 841    }
 842}
 843
 844struct SubdomainsSectionView: View {
 845    let rows: [SubdomainRowViewData]
 846    let loading: Bool
 847    let error: String?
 848    let showsExtendedPlaceholder: Bool
 849
 850    var body: some View {
 851        VStack(alignment: .leading, spacing: 12) {
 852            HStack {
 853                SectionTitleView(title: "Subdomains")
 854                Spacer()
 855                Text("\(rows.count)")
 856                    .font(.system(.caption2, design: .monospaced))
 857                    .foregroundStyle(.secondary)
 858            }
 859
 860            CardView(allowsHorizontalScroll: false) {
 861                if loading {
 862                    ProgressView("Checking certificate transparency…")
 863                        .appLoadingStyle()
 864                } else if rows.isEmpty {
 865                    MessageRowView(text: error ?? "No passive subdomains found", isError: false)
 866                    if showsExtendedPlaceholder {
 867                        MessageRowView(text: "Extended subdomain discovery (Data+)", isError: false)
 868                            .padding(.top, 4)
 869                    }
 870                } else {
 871                    ForEach(rows) { row in
 872                        HStack(spacing: 8) {
 873                            Text(row.hostname)
 874                                .font(.system(.caption, design: .monospaced))
 875                                .foregroundStyle(.primary)
 876                                .textSelection(.enabled)
 877                            Spacer()
 878                            if row.isInteresting {
 879                                Text("Interesting")
 880                                    .font(.system(.caption2, design: .monospaced))
 881                                    .foregroundStyle(.yellow)
 882                                    .padding(.horizontal, 8)
 883                                    .padding(.vertical, 4)
 884                                    .background(Color.yellow.opacity(0.14))
 885                                    .clipShape(Capsule())
 886                            }
 887                        }
 888                    }
 889                    if showsExtendedPlaceholder {
 890                        MessageRowView(text: "Extended subdomain discovery (Data+)", isError: false)
 891                            .padding(.top, 4)
 892                    }
 893                }
 894            }
 895        }
 896    }
 897}
 898
 899struct DNSSectionView: View {
 900    let dnssecLabel: String?
 901    let sections: [DNSRecordSectionViewData]
 902    let ptrMessage: SectionMessageViewData?
 903    let loading: Bool
 904    let sectionError: String?
 905
 906    var body: some View {
 907        VStack(alignment: .leading, spacing: 12) {
 908            HStack(alignment: .top, spacing: 8) {
 909                SectionTitleView(title: "DNS")
 910                Spacer()
 911                if let dnssecLabel {
 912                    Text(dnssecLabel)
 913                        .font(.system(.caption2, design: .monospaced))
 914                        .foregroundStyle(.secondary)
 915                        .multilineTextAlignment(.trailing)
 916                }
 917            }
 918
 919            if loading {
 920                LoadingCardView(text: "Querying DNS…")
 921            } else if let sectionError, sections.isEmpty {
 922                MessageCardView(text: sectionError, isError: true)
 923            } else {
 924                ForEach(sections) { section in
 925                    CardView {
 926                        Text(section.title)
 927                            .font(.system(.subheadline, design: .monospaced))
 928                            .fontWeight(.semibold)
 929                            .foregroundStyle(.cyan)
 930
 931                        if let message = section.message {
 932                            MessageRowView(text: message.text, isError: message.isError)
 933                        }
 934
 935                        ForEach(section.rows) { row in
 936                            LabeledValueRow(row: row)
 937                        }
 938
 939                        if let wildcardTitle = section.wildcardTitle {
 940                            Text(wildcardTitle)
 941                                .font(.system(.caption, design: .monospaced))
 942                                .foregroundStyle(.secondary)
 943                                .padding(.top, 4)
 944                            ForEach(section.wildcardRows) { row in
 945                                LabeledValueRow(row: row)
 946                            }
 947                        }
 948                    }
 949                }
 950
 951                if let ptrMessage {
 952                    CardView {
 953                        Text("PTR")
 954                            .font(.system(.subheadline, design: .monospaced))
 955                            .fontWeight(.semibold)
 956                            .foregroundStyle(.cyan)
 957                        MessageRowView(text: ptrMessage.text, isError: ptrMessage.isError)
 958                    }
 959                }
 960            }
 961        }
 962    }
 963}
 964
 965struct WebSectionView: View {
 966    let certificateRows: [InfoRowViewData]
 967    let sslInfo: SSLCertificateInfo?
 968    let sslLoading: Bool
 969    let sslError: String?
 970    let responseRows: [InfoRowViewData]
 971    let headers: [HTTPHeader]
 972    let headersLoading: Bool
 973    let headersError: String?
 974    let redirects: [RedirectHopViewData]
 975    let redirectLoading: Bool
 976    let redirectError: String?
 977    let finalURL: String?
 978
 979    var body: some View {
 980        VStack(alignment: .leading, spacing: 12) {
 981            SectionTitleView(title: "Web")
 982
 983            CardView {
 984                Text("TLS")
 985                    .font(.system(.subheadline, design: .monospaced))
 986                    .fontWeight(.semibold)
 987                    .foregroundStyle(.cyan)
 988                if sslLoading {
 989                    ProgressView("Checking certificate…")
 990                        .appLoadingStyle()
 991                } else if let sslError {
 992                    MessageRowView(text: sslError, isError: true)
 993                } else {
 994                    ForEach(certificateRows) { row in
 995                        LabeledValueRow(row: row)
 996                    }
 997                    if let sslInfo, !sslInfo.subjectAltNames.isEmpty {
 998                        Text("SANs")
 999                            .font(.system(.caption2, design: .monospaced))
1000                            .foregroundStyle(.secondary)
1001                        ForEach(sslInfo.subjectAltNames, id: \.self) { san in
1002                            Text(san)
1003                                .font(.system(.caption, design: .monospaced))
1004                                .textSelection(.enabled)
1005                        }
1006                    }
1007                }
1008            }
1009
1010            CardView {
1011                Text("Headers")
1012                    .font(.system(.subheadline, design: .monospaced))
1013                    .fontWeight(.semibold)
1014                    .foregroundStyle(.cyan)
1015                if headersLoading {
1016                    ProgressView("Fetching headers…")
1017                        .appLoadingStyle()
1018                } else if let headersError {
1019                    MessageRowView(text: headersError, isError: true)
1020                } else {
1021                    ForEach(responseRows) { row in
1022                        LabeledValueRow(row: row)
1023                    }
1024                    if headers.isEmpty {
1025                        MessageRowView(text: "No HTTP headers returned", isError: false)
1026                    } else {
1027                        ForEach(headers) { header in
1028                            HStack(alignment: .top, spacing: 4) {
1029                                Text(header.name + ":")
1030                                    .font(.system(.caption, design: .monospaced))
1031                                    .foregroundStyle(header.isSecurityHeader ? .yellow : .cyan)
1032                                Text(header.value)
1033                                    .font(.system(.caption, design: .monospaced))
1034                                    .foregroundStyle(.primary)
1035                                    .textSelection(.enabled)
1036                            }
1037                        }
1038                    }
1039                }
1040            }
1041
1042            CardView {
1043                Text("Redirects")
1044                    .font(.system(.subheadline, design: .monospaced))
1045                    .fontWeight(.semibold)
1046                    .foregroundStyle(.cyan)
1047                if redirectLoading {
1048                    ProgressView("Tracing redirects…")
1049                        .appLoadingStyle()
1050                } else if let redirectError {
1051                    MessageRowView(text: redirectError, isError: true)
1052                } else if redirects.isEmpty {
1053                    MessageRowView(text: "No redirect data available", isError: false)
1054                } else {
1055                    if let finalURL {
1056                        LabeledValueRow(row: InfoRowViewData(label: "Final URL", value: finalURL, tone: .secondary))
1057                    }
1058                    ForEach(redirects) { redirect in
1059                        HStack(alignment: .top, spacing: 6) {
1060                            Text(redirect.stepLabel)
1061                                .font(.system(.caption, design: .monospaced))
1062                                .foregroundStyle(.secondary)
1063                                .frame(width: 16, alignment: .trailing)
1064                            Text(redirect.statusCode)
1065                                .font(.system(.caption, design: .monospaced))
1066                                .foregroundStyle(.cyan)
1067                                .frame(width: 36, alignment: .leading)
1068                            Text(redirect.url)
1069                                .font(.system(.caption, design: .monospaced))
1070                                .textSelection(.enabled)
1071                            if redirect.isFinal {
1072                                Text("(final)")
1073                                    .font(.system(.caption2, design: .monospaced))
1074                                    .foregroundStyle(.secondary)
1075                            }
1076                        }
1077                    }
1078                }
1079            }
1080        }
1081    }
1082}
1083
1084struct EmailSectionView: View {
1085    let rows: [EmailRowViewData]
1086    let loading: Bool
1087    let error: String?
1088
1089    var body: some View {
1090        VStack(alignment: .leading, spacing: 12) {
1091            SectionTitleView(title: "Email")
1092            CardView {
1093                if loading {
1094                    ProgressView("Checking email records…")
1095                        .appLoadingStyle()
1096                } else if let error {
1097                    MessageRowView(text: error, isError: true)
1098                } else if rows.isEmpty {
1099                    MessageRowView(text: "No email security records found", isError: false)
1100                } else {
1101                    ForEach(rows) { row in
1102                        VStack(alignment: .leading, spacing: 4) {
1103                            HStack(spacing: 8) {
1104                                Text(row.label)
1105                                    .font(.system(.caption, design: .monospaced))
1106                                    .foregroundStyle(.cyan)
1107                                    .frame(width: 76, alignment: .leading)
1108                                Text(row.status)
1109                                    .font(.system(.caption, design: .monospaced))
1110                                    .foregroundStyle(ResultColors.color(for: row.statusTone))
1111                            }
1112                            Text(row.detail)
1113                                .font(.system(.caption2, design: .monospaced))
1114                                .foregroundStyle(.primary)
1115                                .textSelection(.enabled)
1116                            if let auxiliaryDetail = row.auxiliaryDetail {
1117                                Text(auxiliaryDetail)
1118                                    .font(.system(.caption2, design: .monospaced))
1119                                    .foregroundStyle(.secondary)
1120                            }
1121                        }
1122                    }
1123                }
1124            }
1125        }
1126    }
1127}
1128
1129struct NetworkSectionView: View {
1130    let reachabilityRows: [ReachabilityRowViewData]
1131    let reachabilityLoading: Bool
1132    let reachabilityError: String?
1133    let locationRows: [InfoRowViewData]
1134    let geolocation: IPGeolocation?
1135    let geolocationLoading: Bool
1136    let geolocationError: String?
1137    let standardPortRows: [PortScanRowViewData]
1138    let customPortRows: [PortScanRowViewData]
1139    let portScanLoading: Bool
1140    let portScanError: String?
1141    let customPortScanLoading: Bool
1142    let customPortScanError: String?
1143    let isCloudflareProxied: Bool
1144    @Binding var customPortsExpanded: Bool
1145    @Binding var customPortInput: String
1146    let onScanCustomPorts: () -> Void
1147
1148    var body: some View {
1149        VStack(alignment: .leading, spacing: 12) {
1150            SectionTitleView(title: "Network")
1151
1152            CardView {
1153                Text("Reachability")
1154                    .font(.system(.subheadline, design: .monospaced))
1155                    .fontWeight(.semibold)
1156                    .foregroundStyle(.cyan)
1157                if reachabilityLoading {
1158                    ProgressView("Checking ports…")
1159                        .appLoadingStyle()
1160                } else if let reachabilityError {
1161                    MessageRowView(text: reachabilityError, isError: true)
1162                } else {
1163                    ForEach(reachabilityRows) { row in
1164                        HStack {
1165                            Text(row.portLabel)
1166                                .font(.system(.caption, design: .monospaced))
1167                            Spacer()
1168                            Text(row.latencyLabel)
1169                                .font(.system(.caption2, design: .monospaced))
1170                                .foregroundStyle(.secondary)
1171                            Text(row.statusLabel)
1172                                .font(.system(.caption, design: .monospaced))
1173                                .foregroundStyle(ResultColors.color(for: row.statusTone))
1174                        }
1175                    }
1176                }
1177            }
1178
1179            CardView(allowsHorizontalScroll: false) {
1180                Text("Location")
1181                    .font(.system(.subheadline, design: .monospaced))
1182                    .fontWeight(.semibold)
1183                    .foregroundStyle(.cyan)
1184                if geolocationLoading {
1185                    ProgressView("Looking up location…")
1186                        .appLoadingStyle()
1187                } else if let geolocationError, geolocation == nil {
1188                    MessageRowView(text: geolocationError, isError: geolocationError != "No A record available")
1189                } else if let geolocation {
1190                    ForEach(locationRows) { row in
1191                        LabeledValueRow(row: row)
1192                    }
1193                    if let latitude = geolocation.latitude, let longitude = geolocation.longitude {
1194                        let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
1195                        Map(initialPosition: .region(MKCoordinateRegion(
1196                            center: coordinate,
1197                            span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1)
1198                        ))) {
1199                            Marker(geolocation.ip, coordinate: coordinate)
1200                        }
1201                        .mapStyle(.standard)
1202                        .frame(maxWidth: .infinity)
1203                        .frame(height: 180)
1204                        .cornerRadius(8)
1205                    }
1206                } else {
1207                    MessageRowView(text: "No location data available", isError: false)
1208                }
1209            }
1210
1211            CardView(allowsHorizontalScroll: false) {
1212                Text("Port Scan")
1213                    .font(.system(.subheadline, design: .monospaced))
1214                    .fontWeight(.semibold)
1215                    .foregroundStyle(.cyan)
1216
1217                if isCloudflareProxied {
1218                    Text("Domain is behind Cloudflare's proxy. Results reflect the edge, not the origin.")
1219                        .font(.system(.caption2, design: .monospaced))
1220                        .foregroundStyle(.orange)
1221                        .fixedSize(horizontal: false, vertical: true)
1222                }
1223
1224                if portScanLoading {
1225                    ProgressView("Scanning ports…")
1226                        .appLoadingStyle()
1227                } else if let portScanError, standardPortRows.isEmpty {
1228                    MessageRowView(text: portScanError, isError: true)
1229                } else {
1230                    Text("Standard Ports")
1231                        .font(.system(.caption, design: .monospaced))
1232                        .foregroundStyle(.secondary)
1233                    PortRowsView(rows: standardPortRows)
1234                }
1235
1236                DisclosureGroup("Custom Ports", isExpanded: $customPortsExpanded) {
1237                    VStack(alignment: .leading, spacing: 10) {
1238                        TextField("8888, 9000, 27017", text: $customPortInput)
1239                            .font(.system(.caption, design: .monospaced))
1240                            .textInputAutocapitalization(.never)
1241                            .autocorrectionDisabled()
1242                            .keyboardType(.numberPad)
1243                            .padding(10)
1244                            .background(Color(.systemGray6).opacity(0.5))
1245                            .cornerRadius(6)
1246
1247                        Button("Scan") {
1248                            onScanCustomPorts()
1249                        }
1250                        .buttonStyle(.borderedProminent)
1251                        .disabled(customPortScanLoading)
1252
1253                        if customPortScanLoading {
1254                            ProgressView("Scanning custom ports…")
1255                                .appLoadingStyle()
1256                        } else if let customPortScanError {
1257                            MessageRowView(text: customPortScanError, isError: true)
1258                        } else {
1259                            PortRowsView(rows: customPortRows)
1260                        }
1261                    }
1262                    .padding(.top, 8)
1263                }
1264                .font(.system(.caption, design: .monospaced))
1265                .tint(.secondary)
1266            }
1267        }
1268    }
1269}
1270
1271struct PortRowsView: View {
1272    let rows: [PortScanRowViewData]
1273
1274    var body: some View {
1275        if rows.isEmpty {
1276            MessageRowView(text: "No results", isError: false)
1277        } else {
1278            ForEach(rows) { row in
1279                VStack(alignment: .leading, spacing: 2) {
1280                    HStack {
1281                        Text(row.portLabel)
1282                            .font(.system(.caption, design: .monospaced))
1283                            .frame(width: 52, alignment: .leading)
1284                        Text(row.service)
1285                            .font(.system(.caption, design: .monospaced))
1286                            .foregroundStyle(.primary)
1287                        Spacer()
1288                        if let durationLabel = row.durationLabel {
1289                            Text(durationLabel)
1290                                .font(.system(.caption2, design: .monospaced))
1291                                .foregroundStyle(.secondary)
1292                        }
1293                        Text(row.statusLabel)
1294                            .font(.system(.caption2, design: .monospaced))
1295                            .foregroundStyle(ResultColors.color(for: row.statusTone))
1296                    }
1297                    if let banner = row.banner {
1298                        Text(banner)
1299                            .font(.system(.caption2, design: .monospaced))
1300                            .foregroundStyle(.secondary)
1301                            .padding(.leading, 8)
1302                    }
1303                }
1304            }
1305        }
1306    }
1307}
1308
1309struct SectionTitleView: View {
1310    let title: String
1311
1312    var body: some View {
1313        Text(title)
1314            .font(.system(.headline))
1315            .foregroundStyle(.white)
1316    }
1317}
1318
1319struct CardView<Content: View>: View {
1320    let allowsHorizontalScroll: Bool
1321    let content: Content
1322
1323    init(allowsHorizontalScroll: Bool = true, @ViewBuilder content: () -> Content) {
1324        self.allowsHorizontalScroll = allowsHorizontalScroll
1325        self.content = content()
1326    }
1327
1328    var body: some View {
1329        Group {
1330            if allowsHorizontalScroll {
1331                ScrollView(.horizontal) {
1332                    cardContent
1333                        .scrollTargetLayout()
1334                }
1335                .scrollBounceBehavior(.basedOnSize, axes: .horizontal)
1336            } else {
1337                cardContent
1338                    .frame(maxWidth: .infinity, alignment: .leading)
1339            }
1340        }
1341        .frame(maxWidth: .infinity, alignment: .leading)
1342        .padding(10)
1343        .background(Color(.systemGray6).opacity(0.5))
1344        .cornerRadius(6)
1345    }
1346
1347    private var cardContent: some View {
1348        VStack(alignment: .leading, spacing: 6) {
1349            content
1350        }
1351    }
1352}
1353
1354struct LoadingCardView: View {
1355    let text: String
1356
1357    var body: some View {
1358        CardView {
1359            ProgressView(text)
1360                .appLoadingStyle()
1361                .frame(maxWidth: .infinity, alignment: .center)
1362        }
1363    }
1364}
1365
1366struct MessageCardView: View {
1367    let text: String
1368    let isError: Bool
1369
1370    var body: some View {
1371        CardView {
1372            MessageRowView(text: text, isError: isError)
1373        }
1374    }
1375}
1376
1377struct MessageRowView: View {
1378    let text: String
1379    let isError: Bool
1380
1381    var body: some View {
1382        Label(text, systemImage: isError ? "exclamationmark.triangle.fill" : "info.circle")
1383            .font(.system(.caption, design: .monospaced))
1384            .foregroundStyle(isError ? .red : .secondary)
1385    }
1386}
1387
1388struct LabeledValueRow: View {
1389    let row: InfoRowViewData
1390
1391    var body: some View {
1392        VStack(alignment: .leading, spacing: 2) {
1393            Text(row.label)
1394                .font(.system(.caption2, design: .monospaced))
1395                .foregroundStyle(.secondary)
1396            Text(row.value)
1397                .font(.system(.caption, design: .monospaced))
1398                .foregroundStyle(ResultColors.color(for: row.tone))
1399                .textSelection(.enabled)
1400        }
1401    }
1402}
1403
1404enum ResultColors {
1405    static func color(for tone: ResultTone) -> Color {
1406        switch tone {
1407        case .primary:
1408            return .primary
1409        case .secondary:
1410            return .secondary
1411        case .success:
1412            return .green
1413        case .warning:
1414            return .yellow
1415        case .failure:
1416            return .red
1417        }
1418    }
1419}
1420
1421extension DateFormatter {
1422    static let certDate: DateFormatter = {
1423        let formatter = DateFormatter()
1424        formatter.dateStyle = .medium
1425        formatter.timeStyle = .short
1426        return formatter
1427    }()
1428}
1429
1430private extension View {
1431    func appLoadingStyle() -> some View {
1432        font(.system(.caption, design: .monospaced))
1433    }
1434}
1435
1436private extension String {
1437    var nilIfEmpty: String? {
1438        isEmpty ? nil : self
1439    }
1440}
1441
1442private struct SettingsView: View {
1443    @AppStorage(DNSResolverOption.userDefaultsKey)
1444    private var storedResolverURL = DNSResolverOption.defaultURLString
1445
1446    @State private var resolverOption: DNSResolverOption = .cloudflare
1447    @State private var customResolverURL = DNSResolverOption.defaultURLString
1448
1449    private var customResolverError: String? {
1450        guard resolverOption == .custom else {
1451            return nil
1452        }
1453        return DNSResolverOption.isValidCustomURL(customResolverURL) ? nil : "Resolver URL must start with https://"
1454    }
1455
1456    var body: some View {
1457        Form {
1458            Section {
1459                Picker("Resolver", selection: $resolverOption) {
1460                    ForEach(DNSResolverOption.allCases) { option in
1461                        Text(option.title).tag(option)
1462                    }
1463                }
1464
1465                if resolverOption == .custom {
1466                    TextField("https://resolver.example/dns-query", text: $customResolverURL)
1467                        .textInputAutocapitalization(.never)
1468                        .autocorrectionDisabled()
1469                        .keyboardType(.URL)
1470
1471                    if let customResolverError {
1472                        Text(customResolverError)
1473                            .font(.caption)
1474                            .foregroundStyle(.red)
1475                    }
1476                }
1477            }
1478        }
1479        .navigationTitle("Settings")
1480        .onAppear {
1481            let currentResolverURL = storedResolverURL.trimmingCharacters(in: .whitespacesAndNewlines)
1482            resolverOption = DNSResolverOption.option(for: currentResolverURL)
1483            customResolverURL = resolverOption == .custom ? currentResolverURL : DNSResolverOption.defaultURLString
1484        }
1485        .onChange(of: resolverOption) { _, newValue in
1486            guard let presetURL = newValue.urlString else {
1487                storedResolverURL = customResolverURL.trimmingCharacters(in: .whitespacesAndNewlines)
1488                return
1489            }
1490            storedResolverURL = presetURL
1491        }
1492        .onChange(of: customResolverURL) { _, newValue in
1493            guard resolverOption == .custom else { return }
1494            storedResolverURL = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
1495        }
1496    }
1497}
1498
1499#Preview {
1500    ContentView()
1501}