DomainDig/ContentView.swift

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

1785 lines · 74139 bytes

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