DomainDig/ContentView.swift

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

3392 lines · 142802 bytes

   1import MapKit
   2import SwiftUI
   3import UniformTypeIdentifiers
   4
   5enum LookupInputMode: String, CaseIterable, Identifiable {
   6    case single
   7    case bulk
   8
   9    var id: String { rawValue }
  10}
  11
  12enum ResultSection: String, Hashable {
  13    case domain
  14    case ownership
  15    case dns
  16    case web
  17    case email
  18    case network
  19    case subdomains
  20}
  21
  22private enum LookupInputField: Hashable {
  23    case singleDomain
  24    case bulkDomains
  25}
  26
  27private struct WorkflowNavigationTarget: Hashable {
  28    let workflowID: UUID
  29}
  30
  31struct ContentView: View {
  32    @Environment(\.appDensity) private var appDensity
  33    @Bindable var viewModel: DomainViewModel
  34    @State private var purchaseService = PurchaseService.shared
  35    @State private var navigationPath = NavigationPath()
  36    @FocusState private var focusedInputField: LookupInputField?
  37    @State private var customPortInput = ""
  38    @State private var customPortsExpanded = false
  39    @State private var trackingNoteDraft = ""
  40    @State private var editingTrackedDomain: TrackedDomain?
  41    @State private var inputMode: LookupInputMode = .single
  42    @State private var collapsedSections: Set<ResultSection> = [.network]
  43    @State private var showingCurrentDomainWorkflowSheet = false
  44    @State private var showingBatchWorkflowSheet = false
  45    @State private var showingTimeline = false
  46
  47    var body: some View {
  48        let _ = purchaseService.currentTier
  49
  50        NavigationStack(path: $navigationPath) {
  51            ScrollView(.vertical) {
  52                VStack(spacing: 0) {
  53                    inputSection
  54                    if !viewModel.batchResults.isEmpty || viewModel.batchLookupRunning {
  55                        batchSection
  56                            .padding(.top, appDensity.metrics.cardSpacing)
  57                    }
  58                    if viewModel.hasRun {
  59                        actionButtons
  60                        if !viewModel.resultsLoaded {
  61                            LookupProgressOverviewView(steps: viewModel.activeLoadingLabels)
  62                                .padding(.top, appDensity.metrics.cardSpacing)
  63                        } else if let statusMessage = resultStatusMessage {
  64                            LookupStatusBannerView(message: statusMessage, resultSource: viewModel.currentResultSource)
  65                                .padding(.top, appDensity.metrics.cardSpacing)
  66                        }
  67                        if viewModel.resultsLoaded {
  68                            SummaryView(fields: viewModel.summaryFields)
  69                                .padding(.top, appDensity.metrics.cardSpacing)
  70                            if let report = viewModel.currentReport {
  71                                RiskSummaryCardView(report: report)
  72                                    .padding(.top, appDensity.metrics.cardSpacing)
  73                                InsightsSummaryCardView(insights: report.insights)
  74                                    .padding(.top, appDensity.metrics.cardSpacing)
  75                            }
  76                            if let changeSummary = viewModel.currentChangeSummary {
  77                                DomainChangeSummaryView(summary: changeSummary)
  78                                    .padding(.top, appDensity.metrics.cardSpacing)
  79                            }
  80                        }
  81                        domainOverviewSection
  82                            .padding(.top, appDensity.metrics.sectionSpacing)
  83                        ownershipSection
  84                        .padding(.top, appDensity.metrics.sectionSpacing)
  85                        subdomainsSection
  86                        .padding(.top, appDensity.metrics.sectionSpacing)
  87                        if !viewModel.currentDiffSections.isEmpty {
  88                            DomainDiffView(
  89                                title: "Latest Changes",
  90                                sections: viewModel.currentDiffSections,
  91                                contextNote: viewModel.currentChangeSummary?.contextNote,
  92                                showsUnchanged: false,
  93                                highlightedSectionID: nil
  94                            )
  95                            .padding(.top, appDensity.metrics.sectionSpacing)
  96                        }
  97                        dnsSection
  98                        .padding(.top, appDensity.metrics.sectionSpacing)
  99                        WebSectionView(
 100                            isCollapsed: sectionCollapsedBinding(.web),
 101                            certificateRows: viewModel.webCertificateRows,
 102                            sslInfo: viewModel.sslInfo,
 103                            tlsSummary: viewModel.currentTLSSummary,
 104                            sslLoading: viewModel.sslLoading || viewModel.hstsLoading,
 105                            sslError: viewModel.sslError,
 106                            tlsProvenance: viewModel.currentSnapshot.provenanceBySection[.ssl],
 107                            responseRows: viewModel.webResponseRows,
 108                            headers: viewModel.httpHeaders,
 109                            headersLoading: viewModel.httpHeadersLoading,
 110                            headersError: viewModel.httpHeadersError,
 111                            httpProvenance: viewModel.currentSnapshot.provenanceBySection[.httpHeaders],
 112                            redirects: viewModel.redirectRows,
 113                            redirectLoading: viewModel.redirectChainLoading,
 114                            redirectError: viewModel.redirectChainError,
 115                            redirectProvenance: viewModel.currentSnapshot.provenanceBySection[.redirectChain],
 116                            finalURL: viewModel.currentSnapshot.redirectChain.last?.url
 117                        )
 118                        .padding(.top, appDensity.metrics.sectionSpacing)
 119                        EmailSectionView(
 120                            isCollapsed: sectionCollapsedBinding(.email),
 121                            rows: viewModel.emailRows,
 122                            assessment: viewModel.currentEmailAssessment,
 123                            loading: viewModel.emailSecurityLoading,
 124                            provenance: viewModel.currentSnapshot.provenanceBySection[.emailSecurity],
 125                            confidence: viewModel.currentSnapshot.emailSecurityConfidence,
 126                            error: viewModel.emailSecurityError
 127                        )
 128                        .padding(.top, appDensity.metrics.sectionSpacing)
 129                        NetworkSectionView(
 130                            isCollapsed: sectionCollapsedBinding(.network),
 131                            reachabilityRows: viewModel.reachabilityRows,
 132                            reachabilityLoading: viewModel.reachabilityLoading,
 133                            reachabilityError: viewModel.reachabilityError,
 134                            reachabilityProvenance: viewModel.currentSnapshot.provenanceBySection[.reachability],
 135                            locationRows: viewModel.locationRows,
 136                            geolocation: viewModel.ipGeolocation,
 137                            geolocationLoading: viewModel.ipGeolocationLoading,
 138                            geolocationError: viewModel.ipGeolocationError,
 139                            geolocationProvenance: viewModel.currentSnapshot.provenanceBySection[.ipGeolocation],
 140                            geolocationConfidence: viewModel.currentSnapshot.geolocationConfidence,
 141                            standardPortRows: viewModel.standardPortRows,
 142                            customPortRows: viewModel.customPortRows,
 143                            portScanLoading: viewModel.portScanLoading,
 144                            portScanError: viewModel.portScanError,
 145                            portScanProvenance: viewModel.currentSnapshot.provenanceBySection[.portScan],
 146                            customPortScanLoading: viewModel.customPortScanLoading,
 147                            customPortScanError: viewModel.customPortScanError,
 148                            isCloudflareProxied: viewModel.isCloudflareProxied,
 149                            customPortsExpanded: $customPortsExpanded,
 150                            customPortInput: $customPortInput,
 151                            onScanCustomPorts: runCustomPortScan
 152                        )
 153                        .padding(.top, appDensity.metrics.sectionSpacing)
 154                    } else if !viewModel.recentSearches.isEmpty {
 155                        recentSearchesSection
 156                    }
 157                }
 158                .padding(.horizontal)
 159                .padding(.bottom, 32)
 160            }
 161            .background(
 162                LinearGradient(
 163                    colors: [Color.black, Color(.systemGray6).opacity(0.12)],
 164                    startPoint: .top,
 165                    endPoint: .bottom
 166                )
 167            )
 168            .navigationTitle("DomainDig")
 169            .toolbarColorScheme(.dark, for: .navigationBar)
 170            .preferredColorScheme(.dark)
 171            .toolbar {
 172                ToolbarItem(placement: .topBarTrailing) {
 173                    if viewModel.hasRun {
 174                        Button {
 175                            viewModel.reset()
 176                        } label: {
 177                            Image(systemName: "xmark.circle")
 178                                .foregroundStyle(.secondary)
 179                        }
 180                    }
 181                }
 182
 183                ToolbarItemGroup(placement: .keyboard) {
 184                    Spacer()
 185                    Button("Dismiss Keyboard") {
 186                        focusedInputField = nil
 187                    }
 188                }
 189            }
 190            .navigationDestination(for: WorkflowNavigationTarget.self) { target in
 191                WorkflowDetailView(viewModel: viewModel, workflowID: target.workflowID)
 192            }
 193        }
 194        .onAppear {
 195            focusedInputField = .singleDomain
 196        }
 197        .task {
 198            await viewModel.refreshUsageCredits()
 199        }
 200        .onChange(of: viewModel.searchedDomain) { _, _ in
 201            collapsedSections = defaultCollapsedSections
 202        }
 203        .onChange(of: viewModel.rerunNavigationToken) { _, _ in
 204            navigationPath = NavigationPath()
 205            focusedInputField = nil
 206        }
 207        .onChange(of: inputMode) { _, newValue in
 208            viewModel.clearPresentedResults()
 209            focusedInputField = newValue == .single ? .singleDomain : .bulkDomains
 210        }
 211        .onChange(of: viewModel.domain) { _, newValue in
 212            guard inputMode == .single else { return }
 213            let normalized = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
 214            guard normalized != viewModel.searchedDomain else { return }
 215            guard viewModel.hasRun || !viewModel.batchResults.isEmpty else { return }
 216            viewModel.clearPresentedResults()
 217        }
 218        .onChange(of: viewModel.bulkInput) { _, newValue in
 219            guard inputMode == .bulk else { return }
 220            let normalized = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
 221            guard !normalized.isEmpty || viewModel.hasRun || !viewModel.batchResults.isEmpty else { return }
 222            viewModel.clearPresentedResults()
 223        }
 224        .sheet(item: $editingTrackedDomain) { trackedDomain in
 225            NavigationStack {
 226                Form {
 227                    Section("Tracking Note") {
 228                        TextField("Optional note", text: $trackingNoteDraft, axis: .vertical)
 229                            .lineLimit(3...6)
 230                            .textInputAutocapitalization(.never)
 231                            .autocorrectionDisabled()
 232                    }
 233                }
 234                .navigationTitle(trackedDomain.domain)
 235                .toolbar {
 236                    ToolbarItem(placement: .cancellationAction) {
 237                        Button("Cancel") {
 238                            editingTrackedDomain = nil
 239                        }
 240                    }
 241                    ToolbarItem(placement: .confirmationAction) {
 242                        Button("Save") {
 243                            viewModel.updateNote(trackingNoteDraft, for: trackedDomain)
 244                            editingTrackedDomain = nil
 245                        }
 246                    }
 247                }
 248            }
 249        }
 250        .sheet(isPresented: $showingCurrentDomainWorkflowSheet) {
 251            WorkflowBulkAddSheet(
 252                viewModel: viewModel,
 253                title: "Add Domain to Workflow",
 254                availableDomains: [viewModel.searchedDomain]
 255            )
 256        }
 257        .sheet(isPresented: $showingBatchWorkflowSheet) {
 258            WorkflowBulkAddSheet(
 259                viewModel: viewModel,
 260                title: "Add Batch Domains",
 261                availableDomains: viewModel.batchResults.map(\.domain)
 262            )
 263        }
 264        .sheet(isPresented: $showingTimeline) {
 265            NavigationStack {
 266                TimelineView(viewModel: viewModel, domain: viewModel.searchedDomain)
 267            }
 268        }
 269    }
 270
 271    private var inputSection: some View {
 272        VStack(spacing: appDensity.metrics.cardSpacing + 2) {
 273            Picker("Mode", selection: $inputMode) {
 274                Text("Single").tag(LookupInputMode.single)
 275                Text("Bulk").tag(LookupInputMode.bulk)
 276            }
 277            .pickerStyle(.segmented)
 278
 279            if inputMode == .single {
 280                TextField("e.g. cleberg.net", text: $viewModel.domain)
 281                    .font(appDensity.font(.title3, design: .monospaced))
 282                    .textInputAutocapitalization(.never)
 283                    .autocorrectionDisabled()
 284                    .keyboardType(.URL)
 285                    .padding(.horizontal, 12)
 286                    .padding(.vertical, appDensity.metrics.controlVerticalPadding)
 287                    .background(Color(.systemGray6))
 288                    .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
 289                    .focused($focusedInputField, equals: .singleDomain)
 290                    .onSubmit {
 291                        focusedInputField = nil
 292                        viewModel.run()
 293                    }
 294
 295                Button {
 296                    focusedInputField = nil
 297                    viewModel.run()
 298                } label: {
 299                    Text("Run")
 300                        .font(appDensity.font(.headline, design: .default, weight: .semibold))
 301                        .frame(maxWidth: .infinity)
 302                        .frame(minHeight: appDensity.metrics.controlMinHeight)
 303                }
 304                .buttonStyle(.borderedProminent)
 305                .disabled(viewModel.trimmedDomain.isEmpty)
 306            } else {
 307                if FeatureAccessService.hasAccess(to: .batchOperations) {
 308                    VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
 309                        Text("Paste domains separated by new lines or commas.")
 310                            .font(appDensity.font(.caption))
 311                            .foregroundStyle(.secondary)
 312
 313                        if let batchAllowanceSummary = FeatureAccessService.batchAllowanceSummary() {
 314                            Text(batchAllowanceSummary)
 315                                .font(appDensity.font(.caption2))
 316                                .foregroundStyle(.secondary)
 317                        }
 318
 319                        TextField(
 320                            "example.com\napple.com, openai.com",
 321                            text: $viewModel.bulkInput,
 322                            axis: .vertical
 323                        )
 324                        .font(appDensity.font(.body))
 325                        .textInputAutocapitalization(.never)
 326                        .autocorrectionDisabled()
 327                        .keyboardType(.URL)
 328                        .lineLimit(4...10)
 329                        .padding(.horizontal, 12)
 330                        .padding(.vertical, appDensity.metrics.controlVerticalPadding)
 331                        .background(Color(.systemGray6))
 332                        .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
 333                        .focused($focusedInputField, equals: .bulkDomains)
 334
 335                        Button {
 336                            focusedInputField = nil
 337                            viewModel.runBulkLookup()
 338                        } label: {
 339                            Text(viewModel.batchLookupRunning ? "Running Batch…" : "Run Batch")
 340                                .font(appDensity.font(.headline, design: .default, weight: .semibold))
 341                                .frame(maxWidth: .infinity)
 342                                .frame(minHeight: appDensity.metrics.controlMinHeight)
 343                        }
 344                        .buttonStyle(.borderedProminent)
 345                        .disabled(viewModel.bulkInput.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || viewModel.batchLookupRunning)
 346                    }
 347                } else {
 348                    lockedFeatureCard(
 349                        title: "Batch Operations",
 350                        message: FeatureAccessService.upgradeMessage(for: .batchOperations)
 351                    )
 352                }
 353            }
 354        }
 355        .padding(.vertical, appDensity.metrics.sectionSpacing)
 356    }
 357
 358    private var domainOverviewSection: some View {
 359        let trackedDomain = viewModel.currentTrackedDomain
 360        let workflows = viewModel.currentDomainWorkflows
 361
 362        return DomainSectionView(
 363            isCollapsed: sectionCollapsedBinding(.domain),
 364            rows: viewModel.domainRows,
 365            suggestions: viewModel.suggestionRows,
 366            showSuggestions: viewModel.availabilityResult?.status == .registered || viewModel.suggestionsLoading,
 367            availabilityLoading: viewModel.availabilityLoading,
 368            suggestionsLoading: viewModel.suggestionsLoading,
 369            provenance: viewModel.currentSnapshot.provenanceBySection[.availability],
 370            confidence: viewModel.currentSnapshot.availabilityConfidence,
 371            snapshotNote: viewModel.currentSnapshot.note,
 372            trackedDomain: trackedDomain,
 373            workflows: workflows,
 374            trackingLimitMessage: viewModel.trackingLimitMessage,
 375            pricingLoading: viewModel.domainPricingLoading,
 376            pricingError: viewModel.domainPricingError,
 377            showsPricingPlaceholder: !DataAccessService.hasAccess(to: .domainPricing),
 378            onTrack: {
 379                _ = viewModel.trackCurrentDomain()
 380            },
 381            onTogglePinned: {
 382                guard let trackedDomain else { return }
 383                viewModel.togglePinned(for: trackedDomain)
 384            },
 385            onEditNote: {
 386                guard let trackedDomain else { return }
 387                trackingNoteDraft = trackedDomain.note ?? ""
 388                editingTrackedDomain = trackedDomain
 389            },
 390            onAddToWorkflow: {
 391                showingCurrentDomainWorkflowSheet = true
 392            },
 393            onOpenWorkflow: { workflow in
 394                navigationPath.append(WorkflowNavigationTarget(workflowID: workflow.id))
 395            },
 396            onRunWorkflow: { workflow in
 397                viewModel.rerunCurrentDomain(in: workflow)
 398            }
 399        )
 400    }
 401
 402    private var ownershipSection: some View {
 403        OwnershipSectionView(
 404            isCollapsed: sectionCollapsedBinding(.ownership),
 405            rows: viewModel.ownershipRows,
 406            loading: viewModel.ownershipLoading,
 407            error: viewModel.ownershipError,
 408            provenance: viewModel.currentSnapshot.provenanceBySection[.ownership],
 409            confidence: viewModel.currentSnapshot.ownershipConfidence,
 410            showsHistoryPlaceholder: !DataAccessService.hasAccess(to: .ownershipHistory),
 411            history: viewModel.ownershipHistory,
 412            historyLoading: viewModel.ownershipHistoryLoading,
 413            historyError: viewModel.ownershipHistoryError,
 414            historyCreditStatus: viewModel.ownershipHistoryCreditStatus,
 415            onLoadHistory: {
 416                Task {
 417                    await viewModel.loadOwnershipHistory()
 418                }
 419            }
 420        )
 421    }
 422
 423    private var subdomainsSection: some View {
 424        SubdomainsSectionView(
 425            isCollapsed: sectionCollapsedBinding(.subdomains),
 426            rows: viewModel.subdomainRows,
 427            groups: viewModel.currentSubdomainGroups,
 428            loading: viewModel.subdomainsLoading,
 429            error: viewModel.subdomainsError,
 430            provenance: viewModel.currentSnapshot.provenanceBySection[.subdomains],
 431            confidence: viewModel.currentSnapshot.subdomainConfidence,
 432            showsExtendedPlaceholder: !DataAccessService.hasAccess(to: .extendedSubdomains),
 433            extendedCount: viewModel.extendedSubdomains.count,
 434            extendedLoading: viewModel.extendedSubdomainsLoading,
 435            extendedError: viewModel.extendedSubdomainsError,
 436            extendedCreditStatus: viewModel.extendedSubdomainsCreditStatus,
 437            onLoadExtended: {
 438                Task {
 439                    await viewModel.loadExtendedSubdomains()
 440                }
 441            }
 442        )
 443    }
 444
 445    private var dnsSection: some View {
 446        DNSSectionView(
 447            isCollapsed: sectionCollapsedBinding(.dns),
 448            dnssecLabel: viewModel.dnssecLabel,
 449            patternSummary: viewModel.currentDNSPatterns,
 450            sections: viewModel.dnsRows,
 451            ptrMessage: viewModel.ptrMessage,
 452            loading: viewModel.dnsLoading || viewModel.ptrLoading,
 453            dnsProvenance: viewModel.currentSnapshot.provenanceBySection[.dns],
 454            ptrProvenance: viewModel.currentSnapshot.provenanceBySection[.ptr],
 455            sectionError: viewModel.dnsError,
 456            history: viewModel.dnsHistory,
 457            historyLoading: viewModel.dnsHistoryLoading,
 458            historyError: viewModel.dnsHistoryError,
 459            showsHistoryPlaceholder: !DataAccessService.hasAccess(to: .dnsHistory),
 460            historyCreditStatus: viewModel.dnsHistoryCreditStatus,
 461            onLoadHistory: {
 462                Task {
 463                    await viewModel.loadDNSHistory()
 464                }
 465            }
 466        )
 467    }
 468
 469    private var actionButtons: some View {
 470        HStack {
 471            Spacer()
 472            if viewModel.resultsLoaded {
 473                Menu {
 474                    if !viewModel.isCurrentDomainTracked {
 475                        Button("Track this domain") {
 476                            _ = viewModel.trackCurrentDomain()
 477                        }
 478                    }
 479                    Button("Add to workflow") {
 480                        showingCurrentDomainWorkflowSheet = true
 481                    }
 482                    if !viewModel.historyEntries(for: viewModel.searchedDomain).isEmpty {
 483                        Button("Open timeline") {
 484                            showingTimeline = true
 485                        }
 486                    }
 487                    if FeatureAccessService.hasAccess(to: .advancedExports) {
 488                        Button("Copy report JSON") {
 489                            guard let json = viewModel.exportJSONString() else { return }
 490                            AppClipboard.copy(json)
 491                            AppHaptics.copy()
 492                        }
 493                    } else {
 494                        Button("Copy report JSON") {
 495                            viewModel.upgradePrompt = FeatureAccessService.upgradePrompt(for: .advancedExports)
 496                        }
 497                    }
 498                    Button("Export report") {
 499                        shareSingleResults(format: .text)
 500                    }
 501                } label: {
 502                    Image(systemName: "bolt.circle")
 503                        .font(appDensity.font(.body, design: .default))
 504                        .foregroundStyle(.secondary)
 505                }
 506                Button {
 507                    viewModel.toggleSavedDomain()
 508                } label: {
 509                    Image(systemName: viewModel.isCurrentDomainSaved ? "bookmark.fill" : "bookmark")
 510                        .font(appDensity.font(.body, design: .default))
 511                        .foregroundStyle(viewModel.isCurrentDomainSaved ? .yellow : .secondary)
 512                }
 513                Menu {
 514                    Button("Export TXT") {
 515                        shareSingleResults(format: .text)
 516                    }
 517                    if FeatureAccessService.hasAccess(to: .advancedExports) {
 518                        Button("Export CSV") {
 519                            shareSingleResults(format: .csv)
 520                        }
 521                        Button("Export JSON") {
 522                            shareSingleResults(format: .json)
 523                        }
 524                    } else {
 525                        Button("CSV Export • Available in Pro") {}
 526                            .disabled(true)
 527                        Button("JSON Export • Available in Pro") {}
 528                            .disabled(true)
 529                    }
 530                } label: {
 531                    Image(systemName: "square.and.arrow.up")
 532                        .font(appDensity.font(.body, design: .default))
 533                        .foregroundStyle(.secondary)
 534                }
 535            }
 536        }
 537    }
 538
 539    private var batchSection: some View {
 540        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
 541            HStack {
 542                Spacer()
 543                if viewModel.batchLookupRunning {
 544                    Button("Cancel") {
 545                        viewModel.cancelBatchLookup()
 546                    }
 547                    .buttonStyle(.bordered)
 548                    .font(appDensity.font(.caption))
 549                }
 550                if !viewModel.currentBatchResultEntries.isEmpty {
 551                    Menu {
 552                        Button("Add to Workflow") {
 553                            showingBatchWorkflowSheet = true
 554                        }
 555                        Divider()
 556                        Button("Export Batch TXT") {
 557                            shareBatchResults(format: .text)
 558                        }
 559                        if FeatureAccessService.hasAccess(to: .advancedExports) {
 560                            Button("Export Batch CSV") {
 561                                shareBatchResults(format: .csv)
 562                            }
 563                            Button("Export Batch JSON") {
 564                                shareBatchResults(format: .json)
 565                            }
 566                        } else {
 567                            Button("Batch CSV • Available in Pro") {}
 568                                .disabled(true)
 569                            Button("Batch JSON • Available in Pro") {}
 570                                .disabled(true)
 571                        }
 572                    } label: {
 573                        Label("Export", systemImage: "square.and.arrow.up")
 574                            .font(appDensity.font(.caption))
 575                    }
 576                    .buttonStyle(.bordered)
 577                }
 578            }
 579
 580            BatchResultsView(
 581                viewModel: viewModel,
 582                title: viewModel.batchLookupSource == .watchlistRefresh ? "Tracked Domain Refresh" : "Batch Results"
 583            )
 584        }
 585    }
 586
 587    private var recentSearchesSection: some View {
 588        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
 589            HStack {
 590                Text("RECENT")
 591                    .font(appDensity.font(.caption2))
 592                    .foregroundStyle(.secondary)
 593                Spacer()
 594                Button("Clear") {
 595                    viewModel.clearRecentSearches()
 596                }
 597                .font(appDensity.font(.caption2))
 598                .foregroundStyle(.secondary)
 599            }
 600
 601            ForEach(viewModel.recentSearches, id: \.self) { domain in
 602                Button {
 603                    viewModel.domain = domain
 604                    focusedInputField = nil
 605                    viewModel.run()
 606                } label: {
 607                    Text(domain)
 608                        .font(appDensity.font(.callout))
 609                        .foregroundStyle(.primary)
 610                        .frame(maxWidth: .infinity, alignment: .leading)
 611                        .padding(.vertical, 8)
 612                        .padding(.horizontal, 10)
 613                        .background(Color(.systemGray6).opacity(0.5))
 614                        .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
 615                }
 616            }
 617        }
 618        .padding(.top, appDensity.metrics.cardSpacing)
 619    }
 620
 621    private func runCustomPortScan() {
 622        let ports = parsedCustomPorts(from: customPortInput)
 623        Task {
 624            await viewModel.runCustomPortScan(ports: ports)
 625        }
 626    }
 627
 628    private func lockedFeatureCard(title: String, message: String) -> some View {
 629        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
 630            Text(title)
 631                .font(appDensity.font(.headline, design: .default, weight: .semibold))
 632            Text(message)
 633                .font(appDensity.font(.callout, design: .default))
 634                .foregroundStyle(.secondary)
 635        }
 636        .frame(maxWidth: .infinity, alignment: .leading)
 637        .padding(appDensity.metrics.cardPadding)
 638        .background(Color(.systemGray6))
 639        .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
 640    }
 641
 642    private func parsedCustomPorts(from input: String) -> [UInt16] {
 643        let parts = input.split(separator: ",", omittingEmptySubsequences: true)
 644        var seen = Set<UInt16>()
 645        var ports: [UInt16] = []
 646
 647        for part in parts {
 648            let trimmed = part.trimmingCharacters(in: .whitespacesAndNewlines)
 649            guard let value = UInt16(trimmed), seen.insert(value).inserted else {
 650                continue
 651            }
 652            ports.append(value)
 653            if ports.count == 20 {
 654                break
 655            }
 656        }
 657
 658        return ports
 659    }
 660
 661    private func shareSingleResults(format: DomainExportFormat) {
 662        let (filename, data) = exportPayload(
 663            prefix: "domaindig_single",
 664            format: format,
 665            text: viewModel.exportText(),
 666            csv: viewModel.exportCSV(),
 667            json: viewModel.exportJSONData()
 668        )
 669        ExportPresenter.share(filename: filename, data: data)
 670    }
 671
 672    private func shareBatchResults(format: DomainExportFormat) {
 673        let (filename, data) = exportPayload(
 674            prefix: "domaindig_batch",
 675            format: format,
 676            text: viewModel.exportBatchText(),
 677            csv: viewModel.exportBatchCSV(),
 678            json: viewModel.exportBatchJSONData()
 679        )
 680        ExportPresenter.share(filename: filename, data: data)
 681    }
 682
 683    private func exportPayload(
 684        prefix: String,
 685        format: DomainExportFormat,
 686        text: String,
 687        csv: String,
 688        json: Data?
 689    ) -> (String, Data) {
 690        let formatter = DateFormatter()
 691        formatter.dateFormat = "yyyyMMdd_HHmmss"
 692        let timestamp = formatter.string(from: Date())
 693        let filename = "\(timestamp)_\(prefix).\(format.fileExtension)"
 694        let data: Data
 695
 696        switch format {
 697        case .text:
 698            data = Data(text.utf8)
 699        case .csv:
 700            data = Data(csv.utf8)
 701        case .json:
 702            data = json ?? Data("[]".utf8)
 703        }
 704
 705        return (filename, data)
 706    }
 707
 708    private var defaultCollapsedSections: Set<ResultSection> {
 709        []
 710    }
 711
 712    private var currentPrimaryIP: String? {
 713        viewModel.currentSnapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
 714    }
 715
 716    private var resultStatusMessage: String? {
 717        if let currentStatusMessage = viewModel.currentStatusMessage {
 718            return currentStatusMessage
 719        }
 720
 721        if viewModel.currentResultSource != .live {
 722            return viewModel.currentResultSource.label
 723        }
 724
 725        return nil
 726    }
 727
 728    private func sectionCollapsedBinding(_ section: ResultSection) -> Binding<Bool> {
 729        Binding(
 730            get: { collapsedSections.contains(section) },
 731            set: { isCollapsed in
 732                if isCollapsed {
 733                    collapsedSections.insert(section)
 734                } else {
 735                    collapsedSections.remove(section)
 736                }
 737            }
 738        )
 739    }
 740}
 741
 742struct SummaryView: View {
 743    @Environment(\.appDensity) private var appDensity
 744    let fields: [SummaryFieldViewData]
 745
 746    var body: some View {
 747        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
 748            SectionTitleView(title: "Summary")
 749            LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: appDensity.metrics.cardSpacing) {
 750                ForEach(fields) { field in
 751                    VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing) {
 752                        Text(field.label)
 753                            .font(appDensity.font(.caption2))
 754                            .foregroundStyle(.secondary)
 755                        Text(field.value)
 756                            .font(appDensity.font(.caption))
 757                            .foregroundStyle(ResultColors.color(for: field.tone))
 758                            .lineLimit(2)
 759                            .textSelection(.enabled)
 760                    }
 761                    .frame(minHeight: appDensity.metrics.rowMinHeight + 12, alignment: .topLeading)
 762                    .frame(maxWidth: .infinity, alignment: .leading)
 763                    .padding(appDensity.metrics.cardPadding)
 764                    .background(Color(.systemGray6).opacity(0.5))
 765                    .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
 766                }
 767            }
 768        }
 769    }
 770}
 771
 772struct RiskSummaryCardView: View {
 773    @Environment(\.appDensity) private var appDensity
 774    let report: DomainReport
 775
 776    private var topFactors: [RiskFactor] {
 777        Array(report.riskAssessment.factors.prefix(3))
 778    }
 779
 780    var body: some View {
 781        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
 782            SectionTitleView(title: "Risk")
 783            CardView(allowsHorizontalScroll: false) {
 784                HStack(alignment: .firstTextBaseline) {
 785                    VStack(alignment: .leading, spacing: 4) {
 786                        Text("\(report.riskAssessment.score)")
 787                            .font(appDensity.font(.largeTitle, weight: .bold))
 788                            .foregroundStyle(levelColor)
 789                        Text(report.riskAssessment.level.title)
 790                            .font(appDensity.font(.caption))
 791                            .foregroundStyle(levelColor)
 792                    }
 793                    Spacer()
 794                    Text("Deterministic")
 795                        .font(appDensity.font(.caption2))
 796                        .foregroundStyle(.secondary)
 797                }
 798
 799                if topFactors.isEmpty {
 800                    Text("No major risk factors identified")
 801                        .font(appDensity.font(.caption))
 802                        .foregroundStyle(.secondary)
 803                } else {
 804                    ForEach(Array(topFactors.enumerated()), id: \.offset) { _, factor in
 805                        HStack(alignment: .top, spacing: 8) {
 806                            Circle()
 807                                .fill(factorColor(factor.impact))
 808                                .frame(width: 8, height: 8)
 809                                .padding(.top, 5)
 810                            Text(factor.description)
 811                                .font(appDensity.font(.caption))
 812                                .foregroundStyle(.primary)
 813                        }
 814                    }
 815                }
 816            }
 817        }
 818    }
 819
 820    private var levelColor: Color {
 821        switch report.riskAssessment.level {
 822        case .low:
 823            return .green
 824        case .medium:
 825            return .yellow
 826        case .high:
 827            return .red
 828        }
 829    }
 830
 831    private func factorColor(_ impact: RiskImpact) -> Color {
 832        switch impact {
 833        case .positive:
 834            return .green
 835        case .neutral:
 836            return .secondary
 837        case .negative:
 838            return .red
 839        }
 840    }
 841}
 842
 843struct InsightsSummaryCardView: View {
 844    @Environment(\.appDensity) private var appDensity
 845    let insights: [String]
 846
 847    var body: some View {
 848        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
 849            SectionTitleView(title: "Insights")
 850            CardView(allowsHorizontalScroll: false) {
 851                if insights.isEmpty {
 852                    Text("No deterministic insights triggered")
 853                        .font(appDensity.font(.caption))
 854                        .foregroundStyle(.secondary)
 855                } else {
 856                    ForEach(Array(insights.enumerated()), id: \.offset) { _, insight in
 857                        HStack(alignment: .top, spacing: 8) {
 858                            Image(systemName: "chart.line.uptrend.xyaxis")
 859                                .font(appDensity.font(.caption2))
 860                                .foregroundStyle(.cyan)
 861                                .padding(.top, 2)
 862                            Text(insight)
 863                                .font(appDensity.font(.caption))
 864                                .foregroundStyle(.primary)
 865                        }
 866                    }
 867                }
 868            }
 869        }
 870    }
 871}
 872
 873struct StickyLookupSummaryView: View {
 874    @Environment(\.appDensity) private var appDensity
 875
 876    let domain: String
 877    let availability: DomainAvailabilityStatus?
 878    let primaryIP: String?
 879    let sslInfo: SSLCertificateInfo?
 880    let sslError: String?
 881    let emailSecurity: EmailSecurityResult?
 882    let emailError: String?
 883    let changeSummary: DomainChangeSummary?
 884
 885    var body: some View {
 886        CardView(allowsHorizontalScroll: false) {
 887            VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
 888                HStack(alignment: .center, spacing: 10) {
 889                    Text(domain)
 890                        .font(appDensity.font(.headline, weight: .semibold))
 891                        .foregroundStyle(.primary)
 892                        .lineLimit(1)
 893                    Spacer(minLength: 6)
 894                    AppCopyButton(value: domain, label: "Copy domain")
 895                }
 896
 897                ScrollView(.horizontal, showsIndicators: false) {
 898                    HStack(spacing: 8) {
 899                        AppStatusBadgeView(model: AppStatusFactory.availability(availability))
 900                        AppStatusBadgeView(model: AppStatusFactory.tls(sslInfo: sslInfo, error: sslError))
 901                        AppStatusBadgeView(model: AppStatusFactory.email(emailSecurity, error: emailError))
 902                        AppStatusBadgeView(model: AppStatusFactory.change(changeSummary))
 903                    }
 904                }
 905
 906                if let primaryIP {
 907                    HStack(spacing: 8) {
 908                        Label(primaryIP, systemImage: "network")
 909                            .font(appDensity.font(.caption))
 910                            .foregroundStyle(.secondary)
 911                        Spacer(minLength: 6)
 912                        AppCopyButton(value: primaryIP, label: "Copy IP")
 913                    }
 914                }
 915            }
 916        }
 917        .shadow(color: .black.opacity(0.12), radius: 14, y: 6)
 918    }
 919}
 920
 921struct LookupProgressOverviewView: View {
 922    @Environment(\.appDensity) private var appDensity
 923    let steps: [String]
 924
 925    var body: some View {
 926        CardView(allowsHorizontalScroll: false) {
 927            HStack(spacing: 8) {
 928                ProgressView()
 929                    .controlSize(.small)
 930                VStack(alignment: .leading, spacing: 4) {
 931                    Text("Running lookup…")
 932                        .font(appDensity.font(.caption))
 933                        .foregroundStyle(.primary)
 934                    Text(steps.isEmpty ? "Preparing requests" : steps.joined(separator: " • "))
 935                        .font(appDensity.font(.caption2))
 936                        .foregroundStyle(.secondary)
 937                }
 938                Spacer()
 939            }
 940        }
 941    }
 942}
 943
 944struct LookupStatusBannerView: View {
 945    @Environment(\.appDensity) private var appDensity
 946    let message: String
 947    let resultSource: LookupResultSource
 948
 949    var body: some View {
 950        HStack(spacing: 8) {
 951            Image(systemName: iconName)
 952                .font(.caption)
 953            Text(message)
 954                .font(appDensity.font(.caption))
 955            Spacer()
 956        }
 957        .foregroundStyle(color)
 958        .padding(appDensity.metrics.cardPadding - 2)
 959        .frame(maxWidth: .infinity, alignment: .leading)
 960        .background(color.opacity(0.12))
 961        .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
 962    }
 963
 964    private var color: Color {
 965        switch resultSource {
 966        case .live:
 967            return .green
 968        case .cached:
 969            return .secondary
 970        case .mixed:
 971            return .yellow
 972        case .snapshot:
 973            return .orange
 974        }
 975    }
 976
 977    private var iconName: String {
 978        switch resultSource {
 979        case .live:
 980            return "bolt.horizontal"
 981        case .cached:
 982            return "clock.arrow.trianglehead.counterclockwise.rotate.90"
 983        case .mixed:
 984            return "arrow.triangle.branch"
 985        case .snapshot:
 986            return "archivebox"
 987        }
 988    }
 989}
 990
 991struct DomainChangeSummaryView: View {
 992    @Environment(\.appDensity) private var appDensity
 993    let summary: DomainChangeSummary
 994    @State private var showsDetails = false
 995
 996    var body: some View {
 997        CardView(allowsHorizontalScroll: false) {
 998            HStack {
 999                Label(summary.hasChanges ? "Changed" : "Stable", systemImage: summary.hasChanges ? "arrow.triangle.2.circlepath" : "checkmark.circle")
1000                    .font(appDensity.font(.caption))
1001                    .foregroundStyle(summary.hasChanges ? severityColor(summary.severity) : .green)
1002                Spacer()
1003                Text(summary.severity.title.uppercased())
1004                    .font(appDensity.font(.caption2))
1005                    .foregroundStyle(summary.hasChanges ? severityColor(summary.severity) : .secondary)
1006                    .padding(.horizontal, 8)
1007                    .padding(.vertical, 4)
1008                    .background((summary.hasChanges ? severityColor(summary.severity) : .secondary).opacity(0.16))
1009                    .clipShape(Capsule())
1010                Text(summary.impactClassification.title.uppercased())
1011                    .font(appDensity.font(.caption2))
1012                    .foregroundStyle(impactColor(summary.impactClassification))
1013                    .padding(.horizontal, 8)
1014                    .padding(.vertical, 4)
1015                    .background(impactColor(summary.impactClassification).opacity(0.16))
1016                    .clipShape(Capsule())
1017                Text(summary.generatedAt, style: .time)
1018                    .font(appDensity.font(.caption2))
1019                    .foregroundStyle(.secondary)
1020            }
1021
1022            VStack(alignment: .leading, spacing: 4) {
1023                Text("Inference")
1024                    .font(appDensity.font(.caption2))
1025                    .foregroundStyle(.secondary)
1026                Text(summary.message)
1027                    .font(appDensity.font(.caption))
1028                    .foregroundStyle(.primary)
1029                    .lineLimit(2)
1030            }
1031
1032            if !summary.observedFacts.isEmpty || summary.contextNote != nil {
1033                DisclosureGroup(showsDetails ? "Hide Details" : "Show Details", isExpanded: $showsDetails) {
1034                    VStack(alignment: .leading, spacing: 8) {
1035                        if !summary.observedFacts.isEmpty {
1036                            VStack(alignment: .leading, spacing: 4) {
1037                                Text("Observed")
1038                                    .font(appDensity.font(.caption2))
1039                                    .foregroundStyle(.secondary)
1040                                ForEach(Array(summary.observedFacts.enumerated()), id: \.offset) { _, fact in
1041                                    Text(fact)
1042                                        .font(appDensity.font(.caption))
1043                                        .foregroundStyle(.primary)
1044                                }
1045                            }
1046                        }
1047
1048                        if let riskScoreDelta = summary.riskScoreDelta {
1049                            Text("Risk delta: \(riskScoreDelta >= 0 ? "+" : "")\(riskScoreDelta)")
1050                                .font(appDensity.font(.caption2))
1051                                .foregroundStyle(riskScoreDelta > 0 ? .orange : .secondary)
1052                        }
1053
1054                        if let contextNote = summary.contextNote {
1055                            Text(contextNote)
1056                                .font(appDensity.font(.caption2))
1057                                .foregroundStyle(.orange)
1058                        }
1059                    }
1060                    .padding(.top, 4)
1061                }
1062                .font(appDensity.font(.caption))
1063                .tint(.secondary)
1064            }
1065        }
1066    }
1067
1068    private func severityColor(_ severity: ChangeSeverity) -> Color {
1069        switch severity {
1070        case .low:
1071            return .secondary
1072        case .medium:
1073            return .yellow
1074        case .high:
1075            return .red
1076        }
1077    }
1078
1079    private func impactColor(_ impact: ChangeImpactClassification) -> Color {
1080        switch impact {
1081        case .informational:
1082            return .secondary
1083        case .warning:
1084            return .yellow
1085        case .critical:
1086            return .red
1087        }
1088    }
1089}
1090
1091struct DomainDiffView: View {
1092    let title: String
1093    let sections: [DomainDiffSection]
1094    let contextNote: String?
1095    let showsUnchanged: Bool
1096    let highlightedSectionID: String?
1097
1098    @State private var collapsedSections = Set<String>()
1099    @State private var showsLowSeverity = false
1100
1101    private var filteredSections: [DomainDiffSection] {
1102        sections
1103            .map { section in
1104                let items = section.items.filter { item in
1105                    if !showsUnchanged, !item.hasChanges {
1106                        return false
1107                    }
1108                    if showsLowSeverity {
1109                        return true
1110                    }
1111                    return item.severity >= .medium || (showsUnchanged && item.changeType == .unchanged)
1112                }
1113                return DomainDiffSection(id: section.id, title: section.title, items: items)
1114            }
1115            .filter { !$0.items.isEmpty }
1116    }
1117
1118    private var hasLowSeverityChanges: Bool {
1119        sections.flatMap(\.items).contains { $0.hasChanges && $0.severity == .low }
1120    }
1121
1122    var body: some View {
1123        VStack(alignment: .leading, spacing: 12) {
1124            HStack {
1125                SectionTitleView(title: title)
1126                Spacer()
1127                if hasLowSeverityChanges {
1128                    Button(showsLowSeverity ? "Hide Low" : "Show Low") {
1129                        showsLowSeverity.toggle()
1130                    }
1131                    .buttonStyle(.bordered)
1132                    .font(.system(.caption, design: .monospaced))
1133                }
1134            }
1135            if let contextNote {
1136                MessageCardView(text: contextNote, isError: false)
1137            }
1138            if filteredSections.isEmpty {
1139                MessageCardView(text: "No comparison data available", isError: false)
1140            } else {
1141                ForEach(filteredSections) { section in
1142                    CardView(allowsHorizontalScroll: false) {
1143                        DisclosureGroup(isExpanded: binding(for: section)) {
1144                            let visibleItems = showsUnchanged ? section.items : section.items.filter(\.hasChanges)
1145
1146                            ForEach(visibleItems) { item in
1147                                VStack(alignment: .leading, spacing: 6) {
1148                                    HStack {
1149                                        Text(item.label)
1150                                            .font(.system(.caption, design: .monospaced))
1151                                            .foregroundStyle(.secondary)
1152                                        Spacer()
1153                                        Text("\(item.changeType.marker) \(item.severity.title) • \(changeLabel(for: item.changeType))")
1154                                            .font(.system(.caption2, design: .monospaced))
1155                                            .foregroundStyle(changeColor(for: item))
1156                                            .padding(.horizontal, 8)
1157                                            .padding(.vertical, 4)
1158                                            .background(changeColor(for: item).opacity(0.16))
1159                                            .clipShape(Capsule())
1160                                    }
1161
1162                                    if let oldValue = item.oldValue {
1163                                        VStack(alignment: .leading, spacing: 2) {
1164                                            Text("Old")
1165                                                .font(.system(.caption2, design: .monospaced))
1166                                                .foregroundStyle(.secondary)
1167                                            Text(oldValue)
1168                                                .font(.system(.caption2, design: .monospaced))
1169                                                .foregroundStyle(.secondary)
1170                                                .textSelection(.enabled)
1171                                        }
1172                                    }
1173
1174                                    if let newValue = item.newValue {
1175                                        VStack(alignment: .leading, spacing: 2) {
1176                                            Text("New")
1177                                                .font(.system(.caption2, design: .monospaced))
1178                                                .foregroundStyle(.secondary)
1179                                            Text(newValue)
1180                                                .font(.system(.caption, design: .monospaced))
1181                                                .foregroundStyle(item.hasChanges ? .primary : .secondary)
1182                                                .textSelection(.enabled)
1183                                        }
1184                                    }
1185                                }
1186                                .padding(10)
1187                                .background(item.hasChanges ? changeColor(for: item).opacity(0.08) : Color(.systemGray6).opacity(0.25))
1188                                .cornerRadius(8)
1189                            }
1190                        } label: {
1191                            HStack {
1192                                Text(section.title)
1193                                    .font(.system(.subheadline, design: .monospaced))
1194                                    .fontWeight(.semibold)
1195                                    .foregroundStyle(sectionColor(section))
1196                                Spacer()
1197                                Text(section.severity.title)
1198                                    .font(.system(.caption2, design: .monospaced))
1199                                    .foregroundStyle(sectionColor(section))
1200                            }
1201                        }
1202                    }
1203                    .id(section.id)
1204                    .overlay {
1205                        if highlightedSectionID == section.id {
1206                            RoundedRectangle(cornerRadius: 12)
1207                                .stroke(Color.cyan.opacity(0.55), lineWidth: 1)
1208                        }
1209                    }
1210                }
1211            }
1212        }
1213        .onAppear {
1214            collapsedSections = Set(sections.filter { !showsUnchanged && !$0.hasChanges }.map(\.id))
1215        }
1216    }
1217
1218    private func changeLabel(for changeType: DiffChangeType) -> String {
1219        switch changeType {
1220        case .added:
1221            return "Added"
1222        case .removed:
1223            return "Removed"
1224        case .changed:
1225            return "Changed"
1226        case .unchanged:
1227            return "Unchanged"
1228        }
1229    }
1230
1231    private func changeColor(for item: DomainDiffItem) -> Color {
1232        if item.changeType == .unchanged {
1233            return .secondary
1234        }
1235
1236        switch item.severity {
1237        case .low:
1238            return .blue
1239        case .medium:
1240            return .yellow
1241        case .high:
1242            return .red
1243        }
1244    }
1245
1246    private func sectionColor(_ section: DomainDiffSection) -> Color {
1247        switch section.severity {
1248        case .low:
1249            return .blue
1250        case .medium:
1251            return .yellow
1252        case .high:
1253            return .red
1254        }
1255    }
1256
1257    private func binding(for section: DomainDiffSection) -> Binding<Bool> {
1258        Binding(
1259            get: { !collapsedSections.contains(section.id) },
1260            set: { isExpanded in
1261                if isExpanded {
1262                    collapsedSections.remove(section.id)
1263                } else {
1264                    collapsedSections.insert(section.id)
1265                }
1266            }
1267        )
1268    }
1269}
1270
1271struct TrackedDomainDetailHeaderView: View {
1272    let trackedDomain: TrackedDomain
1273
1274    var body: some View {
1275        VStack(alignment: .leading, spacing: 4) {
1276            if let note = trackedDomain.note?.nilIfEmpty {
1277                LabeledValueRow(row: InfoRowViewData(label: "Tracking Note", value: note, tone: .secondary))
1278            }
1279            HStack(spacing: 8) {
1280                if trackedDomain.isPinned {
1281                    Label("Pinned", systemImage: "pin.fill")
1282                }
1283                Text("Last refresh \(trackedDomain.updatedAt.formatted(date: .abbreviated, time: .shortened))")
1284            }
1285            .font(.system(.caption2, design: .monospaced))
1286            .foregroundStyle(.secondary)
1287        }
1288    }
1289}
1290
1291struct DomainSectionView: View {
1292    @Environment(\.appDensity) private var appDensity
1293    @Binding var isCollapsed: Bool
1294    let rows: [InfoRowViewData]
1295    let suggestions: [DomainSuggestionViewData]
1296    let showSuggestions: Bool
1297    let availabilityLoading: Bool
1298    let suggestionsLoading: Bool
1299    let provenance: SectionProvenance?
1300    let confidence: ConfidenceLevel?
1301    let snapshotNote: String?
1302    let trackedDomain: TrackedDomain?
1303    let workflows: [DomainWorkflow]
1304    let trackingLimitMessage: String?
1305    let pricingLoading: Bool
1306    let pricingError: String?
1307    let showsPricingPlaceholder: Bool
1308    let onTrack: () -> Void
1309    let onTogglePinned: () -> Void
1310    let onEditNote: (() -> Void)?
1311    let onAddToWorkflow: (() -> Void)?
1312    let onOpenWorkflow: ((DomainWorkflow) -> Void)?
1313    let onRunWorkflow: ((DomainWorkflow) -> Void)?
1314
1315    var body: some View {
1316        CollapsibleSectionView(title: "Domain", isCollapsed: $isCollapsed) {
1317            if let trackedDomain {
1318                HStack(spacing: 8) {
1319                    AppStatusBadgeView(model: .init(title: "Tracked", systemImage: "eye.fill", foregroundColor: .green, backgroundColor: .green.opacity(0.16)))
1320                    Button {
1321                        onTogglePinned()
1322                    } label: {
1323                        Image(systemName: trackedDomain.isPinned ? "pin.fill" : "pin")
1324                    }
1325                    .buttonStyle(.bordered)
1326                    .font(appDensity.font(.caption))
1327                    if let onEditNote {
1328                        Button("Note") {
1329                            onEditNote()
1330                        }
1331                        .buttonStyle(.bordered)
1332                        .font(appDensity.font(.caption))
1333                    }
1334                }
1335            } else {
1336                Button("Track") {
1337                    AppHaptics.track()
1338                    onTrack()
1339                }
1340                .buttonStyle(.bordered)
1341                .font(appDensity.font(.caption))
1342            }
1343        } content: {
1344            CardView(allowsHorizontalScroll: false) {
1345                SectionTrustMetadataView(
1346                    provenance: provenance,
1347                    confidence: confidence,
1348                    note: snapshotNote == nil ? nil : "Audit note present"
1349                )
1350                ForEach(rows) { row in
1351                    LabeledValueRow(row: row)
1352                }
1353                if let trackedDomain {
1354                    TrackedDomainDetailHeaderView(trackedDomain: trackedDomain)
1355                        .padding(.top, 4)
1356                } else if let trackingLimitMessage {
1357                    MessageRowView(text: trackingLimitMessage, isError: false)
1358                        .padding(.top, 4)
1359                }
1360                if let onAddToWorkflow {
1361                    Button {
1362                        onAddToWorkflow()
1363                    } label: {
1364                        Label("Add to workflow", systemImage: "plus.rectangle.on.folder")
1365                            .font(appDensity.font(.caption))
1366                    }
1367                    .buttonStyle(.bordered)
1368                    .padding(.top, 4)
1369                }
1370                if !workflows.isEmpty {
1371                    VStack(alignment: .leading, spacing: 8) {
1372                        Text("Part of workflow")
1373                            .font(appDensity.font(.caption))
1374                            .foregroundStyle(.secondary)
1375
1376                        ForEach(workflows) { workflow in
1377                            HStack {
1378                                Text(workflow.name)
1379                                    .font(appDensity.font(.caption))
1380                                    .foregroundStyle(.primary)
1381                                Spacer()
1382                                if let onOpenWorkflow {
1383                                    Button("Open") {
1384                                        onOpenWorkflow(workflow)
1385                                    }
1386                                    .buttonStyle(.bordered)
1387                                    .font(appDensity.font(.caption2))
1388                                }
1389                                if let onRunWorkflow {
1390                                    Button("Run") {
1391                                        onRunWorkflow(workflow)
1392                                    }
1393                                    .buttonStyle(.bordered)
1394                                    .font(appDensity.font(.caption2))
1395                                }
1396                            }
1397                        }
1398                    }
1399                    .padding(.top, 4)
1400                }
1401                if availabilityLoading {
1402                    ProgressView("Checking availability…")
1403                        .appLoadingStyle()
1404                        .padding(.top, 4)
1405                }
1406                if showSuggestions {
1407                    Text("Suggestions")
1408                        .font(appDensity.font(.caption))
1409                        .foregroundStyle(.secondary)
1410                        .padding(.top, 4)
1411                    if suggestionsLoading {
1412                        ProgressView("Checking alternatives…")
1413                            .appLoadingStyle()
1414                    } else if suggestions.isEmpty {
1415                        MessageRowView(text: "No suggestions", isError: false)
1416                    } else {
1417                        ForEach(suggestions) { suggestion in
1418                            HStack {
1419                                Text(suggestion.domain)
1420                                    .font(appDensity.font(.caption))
1421                                    .foregroundStyle(.primary)
1422                                    .textSelection(.enabled)
1423                                Spacer()
1424                                AppStatusBadgeView(model: AppStatusFactory.availability(suggestion.availabilityStatus))
1425                            }
1426                        }
1427                    }
1428                }
1429                if pricingLoading {
1430                    ProgressView("Loading external pricing…")
1431                        .appLoadingStyle()
1432                        .padding(.top, 4)
1433                } else if let pricingError {
1434                    MessageRowView(text: pricingError, isError: false)
1435                        .padding(.top, 4)
1436                } else if showsPricingPlaceholder {
1437                    MessageRowView(text: "Pricing signals available in Pro+", isError: false)
1438                        .padding(.top, 4)
1439                }
1440            }
1441        }
1442    }
1443}
1444
1445struct OwnershipSectionView: View {
1446    @Environment(\.appDensity) private var appDensity
1447    @Binding var isCollapsed: Bool
1448    let rows: [InfoRowViewData]
1449    let loading: Bool
1450    let error: String?
1451    let provenance: SectionProvenance?
1452    let confidence: ConfidenceLevel?
1453    let showsHistoryPlaceholder: Bool
1454    let history: [DomainOwnershipHistoryEvent]
1455    let historyLoading: Bool
1456    let historyError: String?
1457    let historyCreditStatus: UsageCreditStatus?
1458    let onLoadHistory: (() -> Void)?
1459
1460    init(
1461        isCollapsed: Binding<Bool>,
1462        rows: [InfoRowViewData],
1463        loading: Bool,
1464        error: String?,
1465        provenance: SectionProvenance?,
1466        confidence: ConfidenceLevel?,
1467        showsHistoryPlaceholder: Bool,
1468        history: [DomainOwnershipHistoryEvent] = [],
1469        historyLoading: Bool = false,
1470        historyError: String? = nil,
1471        historyCreditStatus: UsageCreditStatus? = nil,
1472        onLoadHistory: (() -> Void)? = nil
1473    ) {
1474        _isCollapsed = isCollapsed
1475        self.rows = rows
1476        self.loading = loading
1477        self.error = error
1478        self.provenance = provenance
1479        self.confidence = confidence
1480        self.showsHistoryPlaceholder = showsHistoryPlaceholder
1481        self.history = history
1482        self.historyLoading = historyLoading
1483        self.historyError = historyError
1484        self.historyCreditStatus = historyCreditStatus
1485        self.onLoadHistory = onLoadHistory
1486    }
1487
1488    var body: some View {
1489        CollapsibleSectionView(title: "Ownership", isCollapsed: $isCollapsed) {
1490            CardView(allowsHorizontalScroll: false) {
1491                SectionTrustMetadataView(provenance: provenance, confidence: confidence)
1492                if loading {
1493                    ProgressView("Fetching RDAP ownership…")
1494                        .appLoadingStyle()
1495                } else {
1496                    ForEach(rows) { row in
1497                        LabeledValueRow(row: row)
1498                    }
1499                    if let error, rows.allSatisfy({ $0.value == "Unavailable" }) {
1500                        MessageRowView(text: error, isError: error != "Unavailable")
1501                            .padding(.top, 4)
1502                    }
1503                    VStack(alignment: .leading, spacing: 8) {
1504                        HStack {
1505                            Text("History")
1506                                .font(appDensity.font(.caption))
1507                                .foregroundStyle(.secondary)
1508                            Spacer()
1509                            if let onLoadHistory, history.isEmpty, !historyLoading, !showsHistoryPlaceholder {
1510                                Button("Load") {
1511                                    onLoadHistory()
1512                                }
1513                                .buttonStyle(.bordered)
1514                                .font(appDensity.font(.caption2))
1515                            }
1516                        }
1517                        if historyLoading {
1518                            ProgressView("Loading history…")
1519                                .appLoadingStyle()
1520                        } else if !history.isEmpty {
1521                            ForEach(history) { event in
1522                                VStack(alignment: .leading, spacing: 3) {
1523                                    Text(event.date.formatted(date: .abbreviated, time: .omitted))
1524                                        .font(appDensity.font(.caption2))
1525                                        .foregroundStyle(.secondary)
1526                                    Text(event.summary)
1527                                        .font(appDensity.font(.caption))
1528                                    Text(event.source)
1529                                        .font(appDensity.font(.caption2))
1530                                        .foregroundStyle(.secondary)
1531                                }
1532                            }
1533                        } else if let historyError {
1534                            MessageRowView(text: historyError, isError: false)
1535                        } else if showsHistoryPlaceholder {
1536                            MessageRowView(text: "Ownership history available in Pro+", isError: false)
1537                        }
1538                    }
1539                }
1540            }
1541        }
1542    }
1543}
1544
1545struct SubdomainsSectionView: View {
1546    @Environment(\.appDensity) private var appDensity
1547    @Binding var isCollapsed: Bool
1548    let rows: [SubdomainRowViewData]
1549    let groups: [SubdomainGroup]
1550    let loading: Bool
1551    let error: String?
1552    let provenance: SectionProvenance?
1553    let confidence: ConfidenceLevel?
1554    let showsExtendedPlaceholder: Bool
1555    let extendedCount: Int
1556    let extendedLoading: Bool
1557    let extendedError: String?
1558    let extendedCreditStatus: UsageCreditStatus?
1559    let onLoadExtended: (() -> Void)?
1560
1561    init(
1562        isCollapsed: Binding<Bool>,
1563        rows: [SubdomainRowViewData],
1564        groups: [SubdomainGroup],
1565        loading: Bool,
1566        error: String?,
1567        provenance: SectionProvenance?,
1568        confidence: ConfidenceLevel?,
1569        showsExtendedPlaceholder: Bool,
1570        extendedCount: Int = 0,
1571        extendedLoading: Bool = false,
1572        extendedError: String? = nil,
1573        extendedCreditStatus: UsageCreditStatus? = nil,
1574        onLoadExtended: (() -> Void)? = nil
1575    ) {
1576        _isCollapsed = isCollapsed
1577        self.rows = rows
1578        self.groups = groups
1579        self.loading = loading
1580        self.error = error
1581        self.provenance = provenance
1582        self.confidence = confidence
1583        self.showsExtendedPlaceholder = showsExtendedPlaceholder
1584        self.extendedCount = extendedCount
1585        self.extendedLoading = extendedLoading
1586        self.extendedError = extendedError
1587        self.extendedCreditStatus = extendedCreditStatus
1588        self.onLoadExtended = onLoadExtended
1589    }
1590
1591    var body: some View {
1592        CollapsibleSectionView(title: "Subdomains", isCollapsed: $isCollapsed, subtitle: "\(rows.count) found") {
1593            CardView(allowsHorizontalScroll: false) {
1594                SectionTrustMetadataView(provenance: provenance, confidence: confidence)
1595                if loading {
1596                    ProgressView("Checking certificate transparency…")
1597                        .appLoadingStyle()
1598                } else if rows.isEmpty {
1599                    MessageRowView(text: error ?? "No passive subdomains found", isError: false)
1600                    if showsExtendedPlaceholder {
1601                        MessageRowView(text: "Extended subdomain discovery available in Pro+", isError: false)
1602                            .padding(.top, 4)
1603                    }
1604                } else {
1605                    if let onLoadExtended, extendedCount == 0, !extendedLoading, !showsExtendedPlaceholder {
1606                        Button("Load extended results") {
1607                            onLoadExtended()
1608                        }
1609                        .buttonStyle(.bordered)
1610                        .font(appDensity.font(.caption2))
1611                    }
1612                    if !groups.isEmpty {
1613                        Text("Groups")
1614                            .font(appDensity.font(.caption2))
1615                            .foregroundStyle(.secondary)
1616                        ForEach(groups) { group in
1617                            HStack {
1618                                Text("\(group.label).*")
1619                                    .font(appDensity.font(.caption))
1620                                    .foregroundStyle(.cyan)
1621                                Spacer()
1622                                Text("\(group.subdomains.count)")
1623                                    .font(appDensity.font(.caption2))
1624                                    .foregroundStyle(.secondary)
1625                            }
1626                        }
1627                    }
1628                    ForEach(rows) { row in
1629                        HStack(spacing: 8) {
1630                            Text(row.hostname)
1631                                .font(appDensity.font(.caption))
1632                                .foregroundStyle(.primary)
1633                                .textSelection(.enabled)
1634                            Spacer()
1635                            if row.isInteresting {
1636                                Text("Interesting")
1637                                    .font(.system(.caption2, design: .monospaced))
1638                                    .foregroundStyle(.yellow)
1639                                    .padding(.horizontal, 8)
1640                                    .padding(.vertical, 4)
1641                                    .background(Color.yellow.opacity(0.14))
1642                                    .clipShape(Capsule())
1643                            }
1644                        }
1645                    }
1646                    if extendedLoading {
1647                        ProgressView("Loading extended subdomains…")
1648                            .appLoadingStyle()
1649                            .padding(.top, 4)
1650                    } else if extendedCount > 0 {
1651                        MessageRowView(text: "\(extendedCount) extended results included", isError: false)
1652                            .padding(.top, 4)
1653                    } else if let extendedError {
1654                        MessageRowView(text: extendedError, isError: false)
1655                            .padding(.top, 4)
1656                    } else if showsExtendedPlaceholder {
1657                        MessageRowView(text: "Extended subdomain discovery available in Pro+", isError: false)
1658                            .padding(.top, 4)
1659                    }
1660                }
1661            }
1662        }
1663    }
1664}
1665
1666struct DNSSectionView: View {
1667    @Environment(\.appDensity) private var appDensity
1668    @Binding var isCollapsed: Bool
1669    let dnssecLabel: String?
1670    let patternSummary: DNSPatternSummary?
1671    let sections: [DNSRecordSectionViewData]
1672    let ptrMessage: SectionMessageViewData?
1673    let loading: Bool
1674    let dnsProvenance: SectionProvenance?
1675    let ptrProvenance: SectionProvenance?
1676    let sectionError: String?
1677    let history: [DNSHistoryEvent]
1678    let historyLoading: Bool
1679    let historyError: String?
1680    let showsHistoryPlaceholder: Bool
1681    let historyCreditStatus: UsageCreditStatus?
1682    let onLoadHistory: (() -> Void)?
1683
1684    init(
1685        isCollapsed: Binding<Bool>,
1686        dnssecLabel: String?,
1687        patternSummary: DNSPatternSummary?,
1688        sections: [DNSRecordSectionViewData],
1689        ptrMessage: SectionMessageViewData?,
1690        loading: Bool,
1691        dnsProvenance: SectionProvenance?,
1692        ptrProvenance: SectionProvenance?,
1693        sectionError: String?,
1694        history: [DNSHistoryEvent] = [],
1695        historyLoading: Bool = false,
1696        historyError: String? = nil,
1697        showsHistoryPlaceholder: Bool = false,
1698        historyCreditStatus: UsageCreditStatus? = nil,
1699        onLoadHistory: (() -> Void)? = nil
1700    ) {
1701        _isCollapsed = isCollapsed
1702        self.dnssecLabel = dnssecLabel
1703        self.patternSummary = patternSummary
1704        self.sections = sections
1705        self.ptrMessage = ptrMessage
1706        self.loading = loading
1707        self.dnsProvenance = dnsProvenance
1708        self.ptrProvenance = ptrProvenance
1709        self.sectionError = sectionError
1710        self.history = history
1711        self.historyLoading = historyLoading
1712        self.historyError = historyError
1713        self.showsHistoryPlaceholder = showsHistoryPlaceholder
1714        self.historyCreditStatus = historyCreditStatus
1715        self.onLoadHistory = onLoadHistory
1716    }
1717
1718    var body: some View {
1719        CollapsibleSectionView(title: "DNS", isCollapsed: $isCollapsed, subtitle: dnssecLabel) {
1720            if loading {
1721                LoadingCardView(text: "Querying DNS…")
1722            } else if let sectionError, sections.isEmpty {
1723                MessageCardView(text: sectionError, isError: true)
1724            } else {
1725                if dnsProvenance != nil {
1726                    CardView(allowsHorizontalScroll: false) {
1727                        SectionTrustMetadataView(provenance: dnsProvenance, confidence: nil)
1728                        if let patternSummary {
1729                            if !patternSummary.providers.isEmpty {
1730                                MessageRowView(text: "Providers: \(patternSummary.providers.joined(separator: ", "))", isError: false)
1731                            }
1732                            if !patternSummary.patterns.isEmpty {
1733                                ForEach(Array(patternSummary.patterns.enumerated()), id: \.offset) { _, pattern in
1734                                    MessageRowView(text: pattern, isError: false)
1735                                }
1736                            }
1737                        }
1738                    }
1739                }
1740                ForEach(sections) { section in
1741                    CardView {
1742                        Text(section.title)
1743                            .font(.system(.subheadline, design: .monospaced))
1744                            .fontWeight(.semibold)
1745                            .foregroundStyle(.cyan)
1746
1747                        if let message = section.message {
1748                            MessageRowView(text: message.text, isError: message.isError)
1749                        }
1750
1751                        ForEach(section.rows) { row in
1752                            LabeledValueRow(row: row)
1753                        }
1754
1755                        if let wildcardTitle = section.wildcardTitle {
1756                            Text(wildcardTitle)
1757                                .font(.system(.caption, design: .monospaced))
1758                                .foregroundStyle(.secondary)
1759                                .padding(.top, 4)
1760                            ForEach(section.wildcardRows) { row in
1761                                LabeledValueRow(row: row)
1762                            }
1763                        }
1764                    }
1765                }
1766
1767                if let ptrMessage {
1768                    CardView {
1769                        Text("PTR")
1770                            .font(.system(.subheadline, design: .monospaced))
1771                            .fontWeight(.semibold)
1772                            .foregroundStyle(.cyan)
1773                        SectionTrustMetadataView(provenance: ptrProvenance, confidence: nil)
1774                        MessageRowView(text: ptrMessage.text, isError: ptrMessage.isError)
1775                    }
1776                }
1777
1778                CardView(allowsHorizontalScroll: false) {
1779                    HStack {
1780                        Text("History")
1781                            .font(appDensity.font(.subheadline, weight: .semibold))
1782                            .foregroundStyle(.cyan)
1783                        Spacer()
1784                        if let onLoadHistory, history.isEmpty, !historyLoading, !showsHistoryPlaceholder {
1785                            Button("Load") {
1786                                onLoadHistory()
1787                            }
1788                            .buttonStyle(.bordered)
1789                            .font(appDensity.font(.caption2))
1790                        }
1791                    }
1792                    if historyLoading {
1793                        ProgressView("Loading DNS history…")
1794                            .appLoadingStyle()
1795                    } else if !history.isEmpty {
1796                        ForEach(history) { event in
1797                            VStack(alignment: .leading, spacing: 3) {
1798                                Text(event.date.formatted(date: .abbreviated, time: .omitted))
1799                                    .font(appDensity.font(.caption2))
1800                                    .foregroundStyle(.secondary)
1801                                Text(event.summary)
1802                                    .font(appDensity.font(.caption))
1803                                if !event.aRecords.isEmpty {
1804                                    Text("A: \(event.aRecords.joined(separator: ", "))")
1805                                        .font(appDensity.font(.caption2))
1806                                        .foregroundStyle(.secondary)
1807                                }
1808                                if !event.nameservers.isEmpty {
1809                                    Text("NS: \(event.nameservers.joined(separator: ", "))")
1810                                        .font(appDensity.font(.caption2))
1811                                        .foregroundStyle(.secondary)
1812                                }
1813                            }
1814                        }
1815                    } else if let historyError {
1816                        MessageRowView(text: historyError, isError: false)
1817                    } else if showsHistoryPlaceholder {
1818                        MessageRowView(text: "DNS history available in Pro+", isError: false)
1819                    }
1820                }
1821            }
1822        }
1823    }
1824}
1825
1826struct WebSectionView: View {
1827    @Environment(\.appDensity) private var appDensity
1828    @Binding var isCollapsed: Bool
1829    let certificateRows: [InfoRowViewData]
1830    let sslInfo: SSLCertificateInfo?
1831    let tlsSummary: WebResultSummary?
1832    let sslLoading: Bool
1833    let sslError: String?
1834    let tlsProvenance: SectionProvenance?
1835    let responseRows: [InfoRowViewData]
1836    let headers: [HTTPHeader]
1837    let headersLoading: Bool
1838    let headersError: String?
1839    let httpProvenance: SectionProvenance?
1840    let redirects: [RedirectHopViewData]
1841    let redirectLoading: Bool
1842    let redirectError: String?
1843    let redirectProvenance: SectionProvenance?
1844    let finalURL: String?
1845
1846    var body: some View {
1847        CollapsibleSectionView(title: "Web", isCollapsed: $isCollapsed) {
1848            CardView {
1849                HStack {
1850                    Text("TLS")
1851                        .font(appDensity.font(.subheadline, weight: .semibold))
1852                        .foregroundStyle(.cyan)
1853                    Spacer()
1854                    if !sslLoading {
1855                        AppStatusBadgeView(model: AppStatusFactory.tls(sslInfo: sslInfo, error: sslError))
1856                    }
1857                }
1858                SectionTrustMetadataView(provenance: tlsProvenance, confidence: nil)
1859                if !sslLoading, let tlsSummary {
1860                    LabeledValueRow(row: InfoRowViewData(label: "TLS Grade", value: tlsSummary.tlsGrade.rawValue, tone: tlsSummary.tlsGrade == .a ? .success : (tlsSummary.tlsGrade == .f ? .failure : .warning)))
1861                    ForEach(Array(tlsSummary.tlsHighlights.enumerated()), id: \.offset) { _, highlight in
1862                        MessageRowView(text: highlight, isError: isTLSHighlightError(highlight))
1863                    }
1864                }
1865                if sslLoading {
1866                    ProgressView("Checking certificate…")
1867                        .appLoadingStyle()
1868                } else if let sslError {
1869                    MessageRowView(text: sslError, isError: true)
1870                } else {
1871                    ForEach(certificateRows) { row in
1872                        LabeledValueRow(row: row)
1873                    }
1874                    if let sslInfo, !sslInfo.subjectAltNames.isEmpty {
1875                        Text("SANs")
1876                            .font(appDensity.font(.caption2))
1877                            .foregroundStyle(.secondary)
1878                        ForEach(sslInfo.subjectAltNames, id: \.self) { san in
1879                            HStack(alignment: .top, spacing: 8) {
1880                                Text(san)
1881                                    .font(appDensity.font(.caption))
1882                                    .lineLimit(nil)
1883                                    .fixedSize(horizontal: false, vertical: true)
1884                                    .textSelection(.enabled)
1885                                Spacer()
1886                                AppCopyButton(value: san, label: "Copy certificate SAN")
1887                            }
1888                        }
1889                    }
1890                }
1891            }
1892
1893            CardView {
1894                Text("Headers")
1895                    .font(appDensity.font(.subheadline, weight: .semibold))
1896                    .foregroundStyle(.cyan)
1897                SectionTrustMetadataView(provenance: httpProvenance, confidence: nil)
1898                if headersLoading {
1899                    ProgressView("Fetching headers…")
1900                        .appLoadingStyle()
1901                } else if let headersError {
1902                    MessageRowView(text: headersError, isError: true)
1903                } else {
1904                    ForEach(responseRows) { row in
1905                        LabeledValueRow(row: row)
1906                    }
1907                    if headers.isEmpty {
1908                        MessageRowView(text: "No HTTP headers returned", isError: false)
1909                    } else {
1910                        ForEach(headers) { header in
1911                            HStack(alignment: .top, spacing: 4) {
1912                                Text(header.name + ":")
1913                                    .font(appDensity.font(.caption))
1914                                    .foregroundStyle(header.isSecurityHeader ? .yellow : .cyan)
1915                                Text(header.value)
1916                                    .font(appDensity.font(.caption))
1917                                    .foregroundStyle(.primary)
1918                                    .textSelection(.enabled)
1919                            }
1920                        }
1921                    }
1922                }
1923            }
1924
1925            CardView {
1926                HStack {
1927                    Text("Redirects")
1928                        .font(appDensity.font(.subheadline, weight: .semibold))
1929                        .foregroundStyle(.cyan)
1930                    Spacer()
1931                    if let finalURL {
1932                        AppCopyButton(value: finalURL, label: "Copy redirect URL")
1933                    }
1934                }
1935                SectionTrustMetadataView(provenance: redirectProvenance, confidence: nil)
1936                if redirectLoading {
1937                    ProgressView("Tracing redirects…")
1938                        .appLoadingStyle()
1939                } else if let redirectError {
1940                    MessageRowView(text: redirectError, isError: true)
1941                } else if redirects.isEmpty {
1942                    MessageRowView(text: "No redirect data available", isError: false)
1943                } else {
1944                    if let finalURL {
1945                        LabeledValueRow(row: InfoRowViewData(label: "Final URL", value: finalURL, tone: .secondary))
1946                    }
1947                    ForEach(redirects) { redirect in
1948                        HStack(alignment: .top, spacing: 6) {
1949                            Text(redirect.stepLabel)
1950                                .font(appDensity.font(.caption))
1951                                .foregroundStyle(.secondary)
1952                                .frame(width: 16, alignment: .trailing)
1953                            Text(redirect.statusCode)
1954                                .font(appDensity.font(.caption))
1955                                .foregroundStyle(.cyan)
1956                                .frame(width: 36, alignment: .leading)
1957                            Text(redirect.url)
1958                                .font(appDensity.font(.caption))
1959                                .textSelection(.enabled)
1960                            AppCopyButton(value: redirect.url, label: "Copy redirect URL")
1961                            if redirect.isFinal {
1962                                Text("(final)")
1963                                    .font(appDensity.font(.caption2))
1964                                    .foregroundStyle(.secondary)
1965                            }
1966                        }
1967                    }
1968                }
1969            }
1970        }
1971    }
1972
1973    private func isTLSHighlightError(_ highlight: String) -> Bool {
1974        let normalized = highlight.lowercased()
1975        if normalized.contains("no weak tls indicators were detected") {
1976            return false
1977        }
1978        return normalized.contains("expires")
1979            || normalized.contains("weak")
1980            || normalized.contains("tls 1.0")
1981            || normalized.contains("tls 1.1")
1982    }
1983}
1984
1985struct EmailSectionView: View {
1986    @Environment(\.appDensity) private var appDensity
1987    @Binding var isCollapsed: Bool
1988    let rows: [EmailRowViewData]
1989    let assessment: EmailSecuritySummary?
1990    let loading: Bool
1991    let provenance: SectionProvenance?
1992    let confidence: ConfidenceLevel?
1993    let error: String?
1994
1995    var body: some View {
1996        CollapsibleSectionView(title: "Email", isCollapsed: $isCollapsed) {
1997            CardView {
1998                SectionTrustMetadataView(provenance: provenance, confidence: confidence)
1999                HStack {
2000                    Spacer()
2001                    AppStatusBadgeView(model: AppStatusFactory.email(nil, error: error))
2002                        .opacity(loading ? 0 : 1)
2003                }
2004                if let assessment, let grade = assessment.grade {
2005                    LabeledValueRow(row: InfoRowViewData(label: "Grade", value: grade.rawValue, tone: grade == .a ? .success : (grade == .f ? .failure : .warning)))
2006                    if !assessment.reasons.isEmpty {
2007                        Text(assessment.reasons.joined(separator: " | "))
2008                            .font(appDensity.font(.caption2))
2009                            .foregroundStyle(.secondary)
2010                    }
2011                }
2012                if loading {
2013                    ProgressView("Checking email records…")
2014                        .appLoadingStyle()
2015                } else if let error {
2016                    MessageRowView(text: error, isError: true)
2017                } else if rows.isEmpty {
2018                    MessageRowView(text: "No email security records found", isError: false)
2019                } else {
2020                    ForEach(rows) { row in
2021                        VStack(alignment: .leading, spacing: 4) {
2022                            HStack(spacing: 8) {
2023                                Text(row.label)
2024                                    .font(appDensity.font(.caption))
2025                                    .foregroundStyle(.cyan)
2026                                    .frame(width: 76, alignment: .leading)
2027                                AppStatusBadgeView(model: emailRowBadge(row))
2028                            }
2029                            Text(row.detail)
2030                                .font(appDensity.font(.caption2))
2031                                .foregroundStyle(.primary)
2032                                .textSelection(.enabled)
2033                            if let auxiliaryDetail = row.auxiliaryDetail {
2034                                Text(auxiliaryDetail)
2035                                    .font(appDensity.font(.caption2))
2036                                    .foregroundStyle(.secondary)
2037                            }
2038                        }
2039                    }
2040                }
2041            }
2042        }
2043    }
2044
2045    private func emailRowBadge(_ row: EmailRowViewData) -> AppStatusBadgeModel {
2046        switch row.statusTone {
2047        case .success:
2048            return .init(title: row.status, systemImage: "checkmark.shield.fill", foregroundColor: .green, backgroundColor: .green.opacity(0.16))
2049        case .warning:
2050            return .init(title: row.status, systemImage: "shield.lefthalf.filled", foregroundColor: .yellow, backgroundColor: .yellow.opacity(0.16))
2051        case .failure:
2052            return .init(title: row.status, systemImage: "minus.circle", foregroundColor: .secondary, backgroundColor: Color(.systemGray5).opacity(0.55))
2053        case .primary, .secondary:
2054            return .init(title: row.status, systemImage: "circle", foregroundColor: .secondary, backgroundColor: Color(.systemGray5).opacity(0.55))
2055        }
2056    }
2057}
2058
2059struct NetworkSectionView: View {
2060    @Environment(\.appDensity) private var appDensity
2061    @Binding var isCollapsed: Bool
2062    let reachabilityRows: [ReachabilityRowViewData]
2063    let reachabilityLoading: Bool
2064    let reachabilityError: String?
2065    let reachabilityProvenance: SectionProvenance?
2066    let locationRows: [InfoRowViewData]
2067    let geolocation: IPGeolocation?
2068    let geolocationLoading: Bool
2069    let geolocationError: String?
2070    let geolocationProvenance: SectionProvenance?
2071    let geolocationConfidence: ConfidenceLevel?
2072    let standardPortRows: [PortScanRowViewData]
2073    let customPortRows: [PortScanRowViewData]
2074    let portScanLoading: Bool
2075    let portScanError: String?
2076    let portScanProvenance: SectionProvenance?
2077    let customPortScanLoading: Bool
2078    let customPortScanError: String?
2079    let isCloudflareProxied: Bool
2080    @Binding var customPortsExpanded: Bool
2081    @Binding var customPortInput: String
2082    let onScanCustomPorts: () -> Void
2083
2084    var body: some View {
2085        CollapsibleSectionView(title: "Network", isCollapsed: $isCollapsed) {
2086            CardView {
2087                Text("Reachability")
2088                    .font(appDensity.font(.subheadline, weight: .semibold))
2089                    .foregroundStyle(.cyan)
2090                SectionTrustMetadataView(provenance: reachabilityProvenance, confidence: nil)
2091                if reachabilityLoading {
2092                    ProgressView("Checking ports…")
2093                        .appLoadingStyle()
2094                } else if let reachabilityError {
2095                    MessageRowView(text: reachabilityError, isError: true)
2096                } else {
2097                    ForEach(reachabilityRows) { row in
2098                        HStack {
2099                            Text(row.portLabel)
2100                                .font(appDensity.font(.caption))
2101                            Spacer()
2102                            Text(row.latencyLabel)
2103                                .font(appDensity.font(.caption2))
2104                                .foregroundStyle(.secondary)
2105                            AppStatusBadgeView(model: reachabilityBadge(row))
2106                        }
2107                    }
2108                }
2109            }
2110
2111            CardView(allowsHorizontalScroll: false) {
2112                Text("Location")
2113                    .font(appDensity.font(.subheadline, weight: .semibold))
2114                    .foregroundStyle(.cyan)
2115                SectionTrustMetadataView(provenance: geolocationProvenance, confidence: geolocationConfidence)
2116                if geolocationLoading {
2117                    ProgressView("Looking up location…")
2118                        .appLoadingStyle()
2119                } else if let geolocationError, geolocation == nil {
2120                    MessageRowView(text: geolocationError, isError: geolocationError != "No A record available")
2121                } else if let geolocation {
2122                    ForEach(locationRows) { row in
2123                        LabeledValueRow(row: row)
2124                    }
2125                    if let latitude = geolocation.latitude, let longitude = geolocation.longitude {
2126                        let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
2127                        Map(initialPosition: .region(MKCoordinateRegion(
2128                            center: coordinate,
2129                            span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1)
2130                        ))) {
2131                            Marker(geolocation.ip, coordinate: coordinate)
2132                        }
2133                        .mapStyle(.standard)
2134                        .frame(maxWidth: .infinity)
2135                        .frame(height: 180)
2136                        .cornerRadius(8)
2137                    }
2138                } else {
2139                    MessageRowView(text: "No location data available", isError: false)
2140                }
2141            }
2142
2143            CardView(allowsHorizontalScroll: false) {
2144                Text("Port Scan")
2145                    .font(appDensity.font(.subheadline, weight: .semibold))
2146                    .foregroundStyle(.cyan)
2147                SectionTrustMetadataView(provenance: portScanProvenance, confidence: nil)
2148
2149                if isCloudflareProxied {
2150                    Text("Domain is behind Cloudflare's proxy. Results reflect the edge, not the origin.")
2151                        .font(appDensity.font(.caption2))
2152                        .foregroundStyle(.orange)
2153                        .fixedSize(horizontal: false, vertical: true)
2154                }
2155
2156                if portScanLoading {
2157                    ProgressView("Scanning ports…")
2158                        .appLoadingStyle()
2159                } else if let portScanError, standardPortRows.isEmpty {
2160                    MessageRowView(text: portScanError, isError: true)
2161                } else {
2162                    Text("Standard Ports")
2163                        .font(.system(.caption, design: .monospaced))
2164                        .foregroundStyle(.secondary)
2165                    PortRowsView(rows: standardPortRows)
2166                }
2167
2168                DisclosureGroup("Custom Ports", isExpanded: $customPortsExpanded) {
2169                    VStack(alignment: .leading, spacing: 10) {
2170                        TextField("8888, 9000, 27017", text: $customPortInput)
2171                            .font(appDensity.font(.caption))
2172                            .textInputAutocapitalization(.never)
2173                            .autocorrectionDisabled()
2174                            .keyboardType(.numberPad)
2175                            .padding(10)
2176                            .background(Color(.systemGray6).opacity(0.5))
2177                            .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
2178
2179                        Button("Scan") {
2180                            AppHaptics.refresh()
2181                            onScanCustomPorts()
2182                        }
2183                        .buttonStyle(.borderedProminent)
2184                        .disabled(customPortScanLoading)
2185
2186                        if customPortScanLoading {
2187                            ProgressView("Scanning custom ports…")
2188                                .appLoadingStyle()
2189                        } else if let customPortScanError {
2190                            MessageRowView(text: customPortScanError, isError: true)
2191                        } else {
2192                            PortRowsView(rows: customPortRows)
2193                        }
2194                    }
2195                    .padding(.top, 8)
2196                }
2197                .font(.system(.caption, design: .monospaced))
2198                .tint(.secondary)
2199            }
2200        }
2201    }
2202
2203    private func reachabilityBadge(_ row: ReachabilityRowViewData) -> AppStatusBadgeModel {
2204        switch row.statusTone {
2205        case .success:
2206            return .init(title: row.statusLabel, systemImage: "checkmark.circle.fill", foregroundColor: .green, backgroundColor: .green.opacity(0.16))
2207        case .warning:
2208            return .init(title: row.statusLabel, systemImage: "exclamationmark.triangle.fill", foregroundColor: .yellow, backgroundColor: .yellow.opacity(0.16))
2209        case .failure:
2210            return .init(title: row.statusLabel, systemImage: "xmark.circle.fill", foregroundColor: .red, backgroundColor: .red.opacity(0.16))
2211        case .primary, .secondary:
2212            return .init(title: row.statusLabel, systemImage: "circle", foregroundColor: .secondary, backgroundColor: Color(.systemGray5).opacity(0.55))
2213        }
2214    }
2215}
2216
2217struct PortRowsView: View {
2218    @Environment(\.appDensity) private var appDensity
2219    let rows: [PortScanRowViewData]
2220
2221    var body: some View {
2222        if rows.isEmpty {
2223            MessageRowView(text: "No results", isError: false)
2224        } else {
2225            ForEach(rows) { row in
2226                VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing - 1) {
2227                    HStack {
2228                        Text(row.portLabel)
2229                            .font(appDensity.font(.caption))
2230                            .frame(width: 52, alignment: .leading)
2231                        Text(row.service)
2232                            .font(appDensity.font(.caption))
2233                            .foregroundStyle(.primary)
2234                        Spacer()
2235                        if let durationLabel = row.durationLabel {
2236                            Text(durationLabel)
2237                                .font(appDensity.font(.caption2))
2238                                .foregroundStyle(.secondary)
2239                        }
2240                        AppStatusBadgeView(model: portBadge(row))
2241                    }
2242                    if let banner = row.banner {
2243                        Text(banner)
2244                            .font(appDensity.font(.caption2))
2245                            .foregroundStyle(.secondary)
2246                            .padding(.leading, 8)
2247                    }
2248                }
2249                .frame(minHeight: appDensity.metrics.rowMinHeight, alignment: .topLeading)
2250            }
2251        }
2252    }
2253
2254    private func portBadge(_ row: PortScanRowViewData) -> AppStatusBadgeModel {
2255        switch row.statusTone {
2256        case .success:
2257            return .init(title: row.statusLabel, systemImage: "checkmark.circle.fill", foregroundColor: .green, backgroundColor: .green.opacity(0.16))
2258        case .warning:
2259            return .init(title: row.statusLabel, systemImage: "exclamationmark.triangle.fill", foregroundColor: .yellow, backgroundColor: .yellow.opacity(0.16))
2260        case .failure:
2261            return .init(title: row.statusLabel, systemImage: "xmark.circle.fill", foregroundColor: .red, backgroundColor: .red.opacity(0.16))
2262        case .primary, .secondary:
2263            return .init(title: row.statusLabel, systemImage: "circle", foregroundColor: .secondary, backgroundColor: Color(.systemGray5).opacity(0.55))
2264        }
2265    }
2266}
2267
2268struct SectionTitleView: View {
2269    @Environment(\.appDensity) private var appDensity
2270    let title: String
2271
2272    var body: some View {
2273        Text(title)
2274            .font(appDensity.font(.headline, design: .default, weight: .semibold))
2275            .foregroundStyle(.white)
2276    }
2277}
2278
2279struct CardView<Content: View>: View {
2280    @Environment(\.appDensity) private var appDensity
2281    let allowsHorizontalScroll: Bool
2282    let content: Content
2283
2284    init(allowsHorizontalScroll: Bool = true, @ViewBuilder content: () -> Content) {
2285        self.allowsHorizontalScroll = allowsHorizontalScroll
2286        self.content = content()
2287    }
2288
2289    var body: some View {
2290        Group {
2291            if allowsHorizontalScroll {
2292                ScrollView(.horizontal) {
2293                    cardContent
2294                        .scrollTargetLayout()
2295                }
2296                .scrollBounceBehavior(.basedOnSize, axes: .horizontal)
2297            } else {
2298                cardContent
2299                    .frame(maxWidth: .infinity, alignment: .leading)
2300            }
2301        }
2302        .frame(maxWidth: .infinity, alignment: .leading)
2303        .padding(appDensity.metrics.cardPadding)
2304        .background(Color(.systemGray6).opacity(0.5))
2305        .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
2306    }
2307
2308    private var cardContent: some View {
2309        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
2310            content
2311        }
2312    }
2313}
2314
2315struct LoadingCardView: View {
2316    let text: String
2317
2318    var body: some View {
2319        CardView {
2320            ProgressView(text)
2321                .appLoadingStyle()
2322                .frame(maxWidth: .infinity, alignment: .center)
2323        }
2324    }
2325}
2326
2327struct MessageCardView: View {
2328    let text: String
2329    let isError: Bool
2330
2331    var body: some View {
2332        CardView {
2333            MessageRowView(text: text, isError: isError)
2334        }
2335    }
2336}
2337
2338struct MessageRowView: View {
2339    @Environment(\.appDensity) private var appDensity
2340    let text: String
2341    let isError: Bool
2342
2343    var body: some View {
2344        Label(text, systemImage: isError ? "exclamationmark.triangle.fill" : "info.circle")
2345            .font(appDensity.font(.caption))
2346            .foregroundStyle(isError ? .red : .secondary)
2347            .lineLimit(nil)
2348            .fixedSize(horizontal: false, vertical: true)
2349    }
2350}
2351
2352struct SectionTrustMetadataView: View {
2353    @Environment(\.appDensity) private var appDensity
2354    let provenance: SectionProvenance?
2355    let confidence: ConfidenceLevel?
2356    let note: String?
2357
2358    init(provenance: SectionProvenance?, confidence: ConfidenceLevel?, note: String? = nil) {
2359        self.provenance = provenance
2360        self.confidence = confidence
2361        self.note = note
2362    }
2363
2364    var body: some View {
2365        if provenance != nil || confidence != nil || note != nil {
2366            VStack(alignment: .leading, spacing: 6) {
2367                HStack(spacing: 8) {
2368                    if let confidence {
2369                        Text("Confidence \(confidence.title)")
2370                            .font(appDensity.font(.caption2))
2371                            .foregroundStyle(.secondary)
2372                    }
2373                    if let provenance {
2374                        Text(provenance.provider ?? provenance.source)
2375                            .font(appDensity.font(.caption2))
2376                            .foregroundStyle(.secondary)
2377                        Text(provenance.resultSource.label)
2378                            .font(appDensity.font(.caption2))
2379                            .foregroundStyle(.secondary)
2380                    }
2381                }
2382                DisclosureGroup("Details") {
2383                    VStack(alignment: .leading, spacing: 4) {
2384                        if let provenance {
2385                            LabeledValueRow(row: .init(label: "Method", value: provenance.source, tone: .secondary))
2386                            if let provider = provenance.provider {
2387                                LabeledValueRow(row: .init(label: "Provider", value: provider, tone: .secondary))
2388                            }
2389                            if let resolver = provenance.resolver {
2390                                LabeledValueRow(row: .init(label: "Resolver", value: resolver, tone: .secondary))
2391                            }
2392                            LabeledValueRow(row: .init(label: "Collected", value: provenance.collectedAt.formatted(date: .abbreviated, time: .shortened), tone: .secondary))
2393                            LabeledValueRow(row: .init(label: "Mode", value: provenance.resultSource.label, tone: .secondary))
2394                        }
2395                        if let note {
2396                            LabeledValueRow(row: .init(label: "Note", value: note, tone: .secondary))
2397                        }
2398                    }
2399                    .padding(.top, 4)
2400                }
2401                .font(appDensity.font(.caption))
2402                .tint(.secondary)
2403            }
2404        }
2405    }
2406}
2407
2408struct LabeledValueRow: View {
2409    @Environment(\.appDensity) private var appDensity
2410    let row: InfoRowViewData
2411
2412    var body: some View {
2413        VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing - 1) {
2414            HStack(alignment: .top, spacing: 8) {
2415                VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing - 1) {
2416                    Text(row.label)
2417                        .font(appDensity.font(.caption2))
2418                        .foregroundStyle(.secondary)
2419                    Text(row.value)
2420                        .font(appDensity.font(.caption))
2421                        .foregroundStyle(ResultColors.color(for: row.tone))
2422                        .lineLimit(nil)
2423                        .fixedSize(horizontal: false, vertical: true)
2424                        .textSelection(.enabled)
2425                }
2426                .frame(maxWidth: .infinity, alignment: .leading)
2427                .layoutPriority(1)
2428                Spacer(minLength: 6)
2429                if !row.value.isEmpty, row.value != "Unavailable" {
2430                    AppCopyButton(value: row.value, label: "Copy \(row.label)")
2431                }
2432            }
2433        }
2434        .frame(minHeight: appDensity.metrics.rowMinHeight, alignment: .topLeading)
2435    }
2436}
2437
2438enum ResultColors {
2439    static func color(for tone: ResultTone) -> Color {
2440        switch tone {
2441        case .primary:
2442            return .primary
2443        case .secondary:
2444            return .secondary
2445        case .success:
2446            return .green
2447        case .warning:
2448            return .yellow
2449        case .failure:
2450            return .red
2451        }
2452    }
2453}
2454
2455extension DateFormatter {
2456    static let certDate: DateFormatter = {
2457        let formatter = DateFormatter()
2458        formatter.dateStyle = .medium
2459        formatter.timeStyle = .short
2460        return formatter
2461    }()
2462}
2463
2464private extension View {
2465    func appLoadingStyle() -> some View {
2466        font(.system(.caption, design: .monospaced))
2467    }
2468}
2469
2470private extension String {
2471    var nilIfEmpty: String? {
2472        isEmpty ? nil : self
2473    }
2474}
2475
2476struct SettingsView: View {
2477    @Environment(\.appDensity) private var appDensity
2478    @Bindable var viewModel: DomainViewModel
2479    @State private var purchaseService = PurchaseService.shared
2480
2481    var body: some View {
2482        let _ = purchaseService.currentTier
2483
2484        List {
2485            Section("Tier") {
2486                LabeledContent("Status", value: purchaseService.currentTier.title)
2487
2488                if purchaseService.currentTier == .free {
2489                    Button("Upgrade") {
2490                        viewModel.isPaywallPresented = true
2491                    }
2492                } else {
2493                    Button("Manage Subscription") {
2494                        Task {
2495                            await purchaseService.manageSubscription()
2496                        }
2497                    }
2498                }
2499
2500                Button(purchaseService.isRestoring ? "Restoring…" : "Restore Purchases") {
2501                    Task {
2502                        await purchaseService.restorePurchases()
2503                    }
2504                }
2505                .disabled(purchaseService.isRestoring || purchaseService.isPurchasing)
2506
2507                if let statusMessage = purchaseService.statusMessage {
2508                    Text(statusMessage)
2509                        .font(appDensity.font(.caption, design: .default))
2510                        .foregroundStyle(.secondary)
2511                }
2512
2513                if let errorMessage = purchaseService.errorMessage {
2514                    Text(errorMessage)
2515                        .font(appDensity.font(.caption, design: .default))
2516                        .foregroundStyle(.red)
2517                }
2518            }
2519
2520            Section("Preferences") {
2521                NavigationLink("Tracked Domains") {
2522                    WatchlistView(viewModel: viewModel)
2523                }
2524
2525                NavigationLink("Workflows") {
2526                    WorkflowsView(viewModel: viewModel)
2527                }
2528
2529                NavigationLink("Display") {
2530                    DisplaySettingsView()
2531                }
2532
2533                NavigationLink("History & Network") {
2534                    HistoryNetworkSettingsView(viewModel: viewModel)
2535                }
2536            }
2537
2538            Section("Services") {
2539                NavigationLink("Monitoring Activity") {
2540                    MonitoringView(viewModel: viewModel)
2541                }
2542
2543                NavigationLink("iCloud Sync") {
2544                    CloudSyncSettingsView()
2545                }
2546
2547                NavigationLink("Monitoring") {
2548                    MonitoringSettingsView(viewModel: viewModel)
2549                }
2550            }
2551
2552            Section("Data") {
2553                NavigationLink("Import & Export") {
2554                    DataPortabilitySettingsView(viewModel: viewModel)
2555                }
2556
2557                NavigationLink("Data Management") {
2558                    DataManagementSettingsView(viewModel: viewModel)
2559                }
2560            }
2561
2562            Section("About") {
2563                NavigationLink("App Info") {
2564                    AboutSettingsView()
2565                }
2566            }
2567        }
2568        .navigationTitle("Settings")
2569    }
2570}
2571
2572private struct DisplaySettingsView: View {
2573    @AppStorage(AppDensity.userDefaultsKey) private var storedDensity = AppDensity.compact.rawValue
2574
2575    var body: some View {
2576        Form {
2577            Section("Display") {
2578                Picker("Density", selection: $storedDensity) {
2579                    ForEach(AppDensity.allCases) { density in
2580                        Text(density.title).tag(density.rawValue)
2581                    }
2582                }
2583            }
2584        }
2585        .navigationTitle("Display")
2586    }
2587}
2588
2589private struct HistoryNetworkSettingsView: View {
2590    @Environment(\.appDensity) private var appDensity
2591    @Bindable var viewModel: DomainViewModel
2592    @AppStorage(DNSResolverOption.userDefaultsKey) private var storedResolverURL = DNSResolverOption.defaultURLString
2593    @AppStorage(AppDensity.userDefaultsKey) private var storedDensity = AppDensity.compact.rawValue
2594
2595    @State private var resolverOption: DNSResolverOption = .cloudflare
2596    @State private var customResolverURL = DNSResolverOption.defaultURLString
2597
2598    private var customResolverError: String? {
2599        guard resolverOption == .custom else { return nil }
2600        return DNSResolverOption.isValidCustomURL(customResolverURL) ? nil : "Resolver URL must start with https://"
2601    }
2602
2603    var body: some View {
2604        Form {
2605            Section("History") {
2606                Picker(
2607                    "Auto-prune",
2608                    selection: Binding(
2609                        get: { viewModel.historyAutoPruneOption },
2610                        set: { viewModel.setHistoryAutoPruneOption($0) }
2611                    )
2612                ) {
2613                    ForEach(HistoryAutoPruneOption.allCases) { option in
2614                        Text(option.title).tag(option)
2615                    }
2616                }
2617
2618                Text("History remains local-first. Auto-prune only trims older local snapshots on this device and defaults to unlimited.")
2619                    .font(appDensity.font(.caption, design: .default))
2620                    .foregroundStyle(.secondary)
2621            }
2622
2623            Section("Network") {
2624                Picker("Resolver", selection: $resolverOption) {
2625                    ForEach(DNSResolverOption.allCases) { option in
2626                        Text(option.title).tag(option)
2627                    }
2628                }
2629
2630                if resolverOption == .custom {
2631                    TextField("https://resolver.example/dns-query", text: $customResolverURL)
2632                        .textInputAutocapitalization(.never)
2633                        .autocorrectionDisabled()
2634                        .keyboardType(.URL)
2635
2636                    if let customResolverError {
2637                        Text(customResolverError)
2638                            .font(appDensity.font(.caption, design: .default))
2639                            .foregroundStyle(.red)
2640                    }
2641                }
2642            }
2643        }
2644        .navigationTitle("History & Network")
2645        .onAppear {
2646            let currentResolverURL = storedResolverURL.trimmingCharacters(in: .whitespacesAndNewlines)
2647            resolverOption = DNSResolverOption.option(for: currentResolverURL)
2648            customResolverURL = resolverOption == .custom ? currentResolverURL : DNSResolverOption.defaultURLString
2649        }
2650        .onChange(of: resolverOption) { _, newValue in
2651            guard let presetURL = newValue.urlString else {
2652                storedResolverURL = customResolverURL.trimmingCharacters(in: .whitespacesAndNewlines)
2653                viewModel.persistCurrentAppSettings(
2654                    resolverURLString: storedResolverURL,
2655                    appDensityRawValue: storedDensity
2656                )
2657                return
2658            }
2659            storedResolverURL = presetURL
2660            viewModel.persistCurrentAppSettings(
2661                resolverURLString: storedResolverURL,
2662                appDensityRawValue: storedDensity
2663            )
2664        }
2665        .onChange(of: customResolverURL) { _, newValue in
2666            guard resolverOption == .custom else { return }
2667            storedResolverURL = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
2668            viewModel.persistCurrentAppSettings(
2669                resolverURLString: storedResolverURL,
2670                appDensityRawValue: storedDensity
2671            )
2672        }
2673        .onChange(of: storedDensity) { _, newValue in
2674            viewModel.persistCurrentAppSettings(
2675                resolverURLString: storedResolverURL,
2676                appDensityRawValue: newValue
2677            )
2678        }
2679    }
2680}
2681
2682private struct CloudSyncSettingsView: View {
2683    @Environment(\.appDensity) private var appDensity
2684    @State private var cloudSyncService = CloudSyncService.shared
2685
2686    var body: some View {
2687        Form {
2688            Section("iCloud Sync") {
2689                Toggle(
2690                    "Enable iCloud Sync",
2691                    isOn: Binding(
2692                        get: { cloudSyncService.isEnabled },
2693                        set: { cloudSyncService.setSyncEnabled($0) }
2694                    )
2695                )
2696
2697                LabeledContent("Status", value: cloudSyncService.status.title)
2698                LabeledContent(
2699                    "Last Sync",
2700                    value: cloudSyncService.lastSyncDate?.formatted(date: .abbreviated, time: .shortened) ?? "Not yet synced"
2701                )
2702
2703                Button(cloudSyncService.status == .syncing ? "Syncing…" : "Sync Now") {
2704                    Task {
2705                        await cloudSyncService.syncNow(trigger: .manual)
2706                    }
2707                }
2708                .disabled(!cloudSyncService.isEnabled || cloudSyncService.status == .syncing)
2709
2710                Text("iCloud Sync stores DomainDig data in your private iCloud account. DomainDig does not operate a sync server. Disabling sync keeps local data on this device.")
2711                    .font(appDensity.font(.caption, design: .default))
2712                    .foregroundStyle(.secondary)
2713
2714                Text(cloudSyncService.detailMessage)
2715                    .font(appDensity.font(.caption, design: .default))
2716                    .foregroundStyle(.secondary)
2717
2718                if let lastErrorMessage = cloudSyncService.lastErrorMessage {
2719                    Text(lastErrorMessage)
2720                        .font(appDensity.font(.caption, design: .default))
2721                        .foregroundStyle(.red)
2722                }
2723            }
2724        }
2725        .navigationTitle("iCloud Sync")
2726        .task {
2727            await cloudSyncService.refreshAvailability()
2728        }
2729    }
2730}
2731
2732private struct MonitoringSettingsView: View {
2733    @Environment(\.appDensity) private var appDensity
2734    @Bindable var viewModel: DomainViewModel
2735
2736    private var notificationAuthorizationLabel: String {
2737        switch viewModel.monitoringNotificationStatus {
2738        case .authorized, .provisional, .ephemeral:
2739            return "Allowed"
2740        case .denied:
2741            return "Denied"
2742        case .notDetermined:
2743            return "Not Requested"
2744        @unknown default:
2745            return "Unknown"
2746        }
2747    }
2748
2749    var body: some View {
2750        Form {
2751            Section("Monitoring") {
2752                Toggle(
2753                    "Enable Background Monitoring",
2754                    isOn: Binding(
2755                        get: { viewModel.monitoringSettings.isEnabled },
2756                        set: { viewModel.setMonitoringEnabled($0) }
2757                    )
2758                )
2759
2760                Picker(
2761                    "Base Interval",
2762                    selection: Binding(
2763                        get: { MonitoringBaseInterval.nearest(to: viewModel.monitoringSettings.baseInterval) },
2764                        set: { viewModel.setMonitoringBaseInterval($0) }
2765                    )
2766                ) {
2767                    ForEach(MonitoringBaseInterval.allCases) { interval in
2768                        Text(interval.title).tag(interval)
2769                    }
2770                }
2771
2772                Toggle(
2773                    "Adaptive Monitoring",
2774                    isOn: Binding(
2775                        get: { viewModel.monitoringSettings.adaptiveEnabled },
2776                        set: { viewModel.setMonitoringAdaptiveEnabled($0) }
2777                    )
2778                )
2779
2780                Picker(
2781                    "Sensitivity",
2782                    selection: Binding(
2783                        get: { viewModel.monitoringSettings.sensitivity },
2784                        set: { viewModel.setMonitoringSensitivity($0) }
2785                    )
2786                ) {
2787                    ForEach(MonitoringSensitivity.allCases) { sensitivity in
2788                        Text(sensitivity.title).tag(sensitivity)
2789                    }
2790                }
2791
2792                let quietHoursStart = viewModel.monitoringSettings.quietHours?.startHour ?? 22
2793                let quietHoursEnd = viewModel.monitoringSettings.quietHours?.endHour ?? 7
2794                Toggle(
2795                    "Quiet Hours",
2796                    isOn: Binding(
2797                        get: { viewModel.monitoringSettings.quietHours != nil },
2798                        set: { isEnabled in
2799                            viewModel.setMonitoringQuietHours(
2800                                startHour: quietHoursStart,
2801                                endHour: quietHoursEnd,
2802                                isEnabled: isEnabled
2803                            )
2804                        }
2805                    )
2806                )
2807
2808                if viewModel.monitoringSettings.quietHours != nil {
2809                    Picker(
2810                        "Quiet Starts",
2811                        selection: Binding(
2812                            get: { quietHoursStart },
2813                            set: { startHour in
2814                                viewModel.setMonitoringQuietHours(
2815                                    startHour: startHour,
2816                                    endHour: quietHoursEnd,
2817                                    isEnabled: true
2818                                )
2819                            }
2820                        )
2821                    ) {
2822                        ForEach(0..<24, id: \.self) { hour in
2823                            Text(Self.monitoringHourLabel(for: hour)).tag(hour)
2824                        }
2825                    }
2826
2827                    Picker(
2828                        "Quiet Ends",
2829                        selection: Binding(
2830                            get: { quietHoursEnd },
2831                            set: { endHour in
2832                                viewModel.setMonitoringQuietHours(
2833                                    startHour: quietHoursStart,
2834                                    endHour: endHour,
2835                                    isEnabled: true
2836                                )
2837                            }
2838                        )
2839                    ) {
2840                        ForEach(0..<24, id: \.self) { hour in
2841                            Text(Self.monitoringHourLabel(for: hour)).tag(hour)
2842                        }
2843                    }
2844                }
2845
2846                Picker(
2847                    "Domains",
2848                    selection: Binding(
2849                        get: { viewModel.monitoringSettings.scope },
2850                        set: { viewModel.setMonitoringScope($0) }
2851                    )
2852                ) {
2853                    ForEach(MonitoringScope.allCases) { scope in
2854                        Text(scope.title).tag(scope)
2855                    }
2856                }
2857
2858                if viewModel.monitoringSettings.scope == .selectedOnly {
2859                    ForEach(viewModel.trackedDomains) { trackedDomain in
2860                        Toggle(
2861                            trackedDomain.domain,
2862                            isOn: Binding(
2863                                get: { viewModel.monitoringSettings.selectedDomainIDs.contains(trackedDomain.id) },
2864                                set: { viewModel.setMonitoringSelection(for: trackedDomain, isSelected: $0) }
2865                            )
2866                        )
2867                    }
2868                }
2869
2870                Toggle(
2871                    "Local Alerts",
2872                    isOn: Binding(
2873                        get: { viewModel.monitoringSettings.alertsEnabled },
2874                        set: { isEnabled in
2875                            if isEnabled {
2876                                Task {
2877                                    await viewModel.requestMonitoringNotificationAuthorization()
2878                                }
2879                            } else {
2880                                viewModel.setMonitoringAlertsEnabled(false)
2881                            }
2882                        }
2883                    )
2884                )
2885
2886                Picker(
2887                    "Notify For",
2888                    selection: Binding(
2889                        get: { viewModel.monitoringSettings.alertFilter },
2890                        set: { viewModel.setMonitoringAlertFilter($0) }
2891                    )
2892                ) {
2893                    ForEach(MonitoringAlertFilter.allCases) { filter in
2894                        Text(filter.title).tag(filter)
2895                    }
2896                }
2897
2898                LabeledContent("Background Refresh", value: DomainMonitoringScheduler.shared.backgroundRefreshStatusDescription())
2899                LabeledContent("Notification Access", value: notificationAuthorizationLabel)
2900
2901                if let monitoringStatusMessage = viewModel.monitoringStatusMessage {
2902                    Text(monitoringStatusMessage)
2903                        .font(appDensity.font(.caption, design: .default))
2904                        .foregroundStyle(.secondary)
2905                }
2906
2907                if !FeatureAccessService.hasAccess(to: .automatedMonitoring) {
2908                    Text("Background monitoring and alerts are available in Pro.")
2909                        .font(appDensity.font(.caption, design: .default))
2910                        .foregroundStyle(.secondary)
2911                }
2912            }
2913        }
2914        .navigationTitle("Monitoring")
2915        .onAppear {
2916            viewModel.refreshMonitoringState()
2917            Task {
2918                await viewModel.refreshMonitoringAuthorizationStatus()
2919            }
2920        }
2921    }
2922
2923    private static func monitoringHourLabel(for hour: Int) -> String {
2924        let formatter = DateFormatter()
2925        formatter.dateFormat = "h a"
2926        let components = DateComponents(calendar: .current, hour: hour)
2927        return components.date.map(formatter.string(from:)) ?? "\(hour):00"
2928    }
2929}
2930
2931private struct DataPortabilitySettingsView: View {
2932    private enum ImportTarget {
2933        case backup
2934        case trackedDomains
2935        case workflows
2936
2937        var expectedKind: DataPortabilityImportKind {
2938            switch self {
2939            case .backup:
2940                return .backup
2941            case .trackedDomains:
2942                return .trackedDomains
2943            case .workflows:
2944                return .workflows
2945            }
2946        }
2947
2948        var allowedContentTypes: [UTType] {
2949            switch self {
2950            case .backup:
2951                return [UTType.json]
2952            case .trackedDomains, .workflows:
2953                return [UTType.json, UTType.commaSeparatedText]
2954            }
2955        }
2956    }
2957
2958    @Environment(\.appDensity) private var appDensity
2959    @Bindable var viewModel: DomainViewModel
2960
2961    @State private var importMode: DataPortabilityImportMode = .merge
2962    @State private var activeImportTarget: ImportTarget?
2963    @State private var pendingImportTarget: ImportTarget?
2964    @State private var importDebugStatus: String?
2965    @State private var pendingImportPreview: DataImportPreview?
2966    @State private var pendingImportError: String?
2967    @State private var showReplaceImportConfirmation = false
2968
2969    var body: some View {
2970        Form {
2971            Section("Import & Export") {
2972                Picker("Import Mode", selection: $importMode) {
2973                    ForEach(DataPortabilityImportMode.allCases) { mode in
2974                        Text(mode.title).tag(mode)
2975                    }
2976                }
2977
2978                Text(importMode.explanation)
2979                    .font(appDensity.font(.caption, design: .default))
2980                    .foregroundStyle(.secondary)
2981
2982                Button("Export Full Backup") {
2983                    exportFullBackup()
2984                }
2985
2986                Button("Import Backup") {
2987                    recordImportDebugStatus("Tapped Import Backup")
2988                    pendingImportTarget = .backup
2989                    activeImportTarget = .backup
2990                }
2991
2992                Menu("Export Tracked Domains") {
2993                    Button("JSON") {
2994                        exportPortableTrackedDomainsJSON()
2995                    }
2996                    Button("CSV") {
2997                        exportPortableTrackedDomainsCSV()
2998                    }
2999                }
3000
3001                Button("Import Tracked Domains") {
3002                    recordImportDebugStatus("Tapped Import Tracked Domains")
3003                    pendingImportTarget = .trackedDomains
3004                    activeImportTarget = .trackedDomains
3005                }
3006
3007                Menu("Export Workflows") {
3008                    Button("JSON") {
3009                        exportPortableWorkflowsJSON()
3010                    }
3011                    Button("CSV") {
3012                        exportPortableWorkflowsCSV()
3013                    }
3014                }
3015
3016                Button("Import Workflows") {
3017                    recordImportDebugStatus("Tapped Import Workflows")
3018                    pendingImportTarget = .workflows
3019                    activeImportTarget = .workflows
3020                }
3021
3022                Button("Export History") {
3023                    exportPortableHistoryJSON()
3024                }
3025            }
3026
3027            Section("Local Data") {
3028                LabeledContent("Tracked Domains", value: "\(viewModel.dataLifecycleSummary.trackedDomains)")
3029                LabeledContent("History Snapshots", value: "\(viewModel.dataLifecycleSummary.historySnapshots)")
3030                LabeledContent("Workflows", value: "\(viewModel.dataLifecycleSummary.workflows)")
3031                LabeledContent("Cached Items", value: "\(viewModel.dataLifecycleSummary.cachedItems)")
3032                LabeledContent("Monitoring Logs", value: "\(viewModel.dataLifecycleSummary.monitoringLogs)")
3033
3034                Text("Data stays on this device unless you export it. Backup files can include domain history, monitoring settings, and notes. Imported files are processed on-device.")
3035                    .font(appDensity.font(.caption, design: .default))
3036                    .foregroundStyle(.secondary)
3037
3038                if let portabilityStatusMessage = viewModel.portabilityStatusMessage {
3039                    Text(portabilityStatusMessage)
3040                        .font(appDensity.font(.caption, design: .default))
3041                        .foregroundStyle(.secondary)
3042                }
3043            }
3044
3045            #if DEBUG
3046            if let importDebugStatus {
3047                Section("Import Debug") {
3048                    Text(importDebugStatus)
3049                        .font(appDensity.font(.caption, design: .default))
3050                        .foregroundStyle(.secondary)
3051                        .textSelection(.enabled)
3052                }
3053            }
3054            #endif
3055        }
3056        .navigationTitle("Import & Export")
3057        .alert("Replace local data?", isPresented: $showReplaceImportConfirmation) {
3058            Button("Replace", role: .destructive) {
3059                applyPendingImport()
3060            }
3061            Button("Cancel", role: .cancel) {}
3062        } message: {
3063            Text("Replace mode overwrites local data covered by the imported file and may remove items that are only on this device.")
3064        }
3065        .alert("Import Error", isPresented: Binding(
3066            get: { pendingImportError != nil },
3067            set: { if !$0 { pendingImportError = nil } }
3068        )) {
3069            Button("OK", role: .cancel) {}
3070        } message: {
3071            Text(pendingImportError ?? "The import could not be completed.")
3072        }
3073        .sheet(isPresented: Binding(
3074            get: { pendingImportPreview != nil },
3075            set: { if !$0 { pendingImportPreview = nil } }
3076        )) {
3077            if let pendingImportPreview {
3078                DataImportPreviewSheet(
3079                    preview: pendingImportPreview,
3080                    mode: importMode,
3081                    onCancel: {
3082                        self.pendingImportPreview = nil
3083                    },
3084                    onApply: {
3085                        if importMode == .replace {
3086                            showReplaceImportConfirmation = true
3087                        } else {
3088                            applyPendingImport()
3089                        }
3090                    }
3091                )
3092            }
3093        }
3094        .fileImporter(
3095            isPresented: Binding(
3096                get: { activeImportTarget != nil },
3097                set: { if !$0 { activeImportTarget = nil } }
3098            ),
3099            allowedContentTypes: activeImportTarget?.allowedContentTypes ?? [UTType.json],
3100            allowsMultipleSelection: false
3101        ) { result in
3102            guard let pendingImportTarget else {
3103                recordImportDebugStatus("fileImporter returned with no active target")
3104                return
3105            }
3106            recordImportDebugStatus("fileImporter returned for \(pendingImportTarget.expectedKind.rawValue)")
3107            handleImportResult(result, expectedKind: pendingImportTarget.expectedKind)
3108            self.pendingImportTarget = nil
3109            self.activeImportTarget = nil
3110        }
3111        .onAppear {
3112            viewModel.refreshDataLifecycleSummary()
3113        }
3114    }
3115
3116    private func exportFullBackup() {
3117        guard let data = viewModel.exportFullBackupData() else { return }
3118        ExportPresenter.share(filename: portabilityFilename(suffix: "backup", fileExtension: "json"), data: data)
3119    }
3120
3121    private func exportPortableTrackedDomainsJSON() {
3122        guard let data = viewModel.exportPortableTrackedDomainsJSONData() else { return }
3123        ExportPresenter.share(filename: portabilityFilename(suffix: "tracked_domains", fileExtension: "json"), data: data)
3124    }
3125
3126    private func exportPortableTrackedDomainsCSV() {
3127        ExportPresenter.share(
3128            filename: portabilityFilename(suffix: "tracked_domains", fileExtension: "csv"),
3129            contents: viewModel.exportPortableTrackedDomainsCSV()
3130        )
3131    }
3132
3133    private func exportPortableWorkflowsJSON() {
3134        guard let data = viewModel.exportPortableWorkflowsJSONData() else { return }
3135        ExportPresenter.share(filename: portabilityFilename(suffix: "workflows", fileExtension: "json"), data: data)
3136    }
3137
3138    private func exportPortableWorkflowsCSV() {
3139        ExportPresenter.share(
3140            filename: portabilityFilename(suffix: "workflows", fileExtension: "csv"),
3141            contents: viewModel.exportPortableWorkflowsCSV()
3142        )
3143    }
3144
3145    private func exportPortableHistoryJSON() {
3146        guard let data = viewModel.exportPortableHistoryJSONData() else { return }
3147        ExportPresenter.share(filename: portabilityFilename(suffix: "history", fileExtension: "json"), data: data)
3148    }
3149
3150    private func handleImportResult(
3151        _ result: Result<[URL], Error>,
3152        expectedKind: DataPortabilityImportKind
3153    ) {
3154        DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult expectedKind=\(expectedKind.rawValue)")
3155        recordImportDebugStatus("handleImportResult started for \(expectedKind.rawValue)")
3156        do {
3157            let urls = try result.get()
3158            guard let url = urls.first else {
3159                DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult noURLReturned")
3160                recordImportDebugStatus("No URL returned from picker")
3161                return
3162            }
3163            DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult selectedURL=\(url.absoluteString)")
3164            recordImportDebugStatus("Selected \(url.lastPathComponent)")
3165            let shouldStopAccessing = url.startAccessingSecurityScopedResource()
3166            DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult securityScopeGranted=\(shouldStopAccessing)")
3167            recordImportDebugStatus("Security scope granted: \(shouldStopAccessing)")
3168            defer {
3169                if shouldStopAccessing {
3170                    url.stopAccessingSecurityScopedResource()
3171                    DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult securityScopeReleased")
3172                }
3173            }
3174
3175            let data = try Data(contentsOf: url)
3176            DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult dataRead bytes=\(data.count) fileName=\(url.lastPathComponent)")
3177            recordImportDebugStatus("Read \(data.count) bytes from \(url.lastPathComponent)")
3178            let preview = try viewModel.prepareDataImport(
3179                data: data,
3180                fileName: url.lastPathComponent,
3181                mode: importMode
3182            )
3183            DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult previewReady previewKind=\(preview.kind.rawValue) expectedKind=\(expectedKind.rawValue)")
3184            recordImportDebugStatus("Preview ready: \(preview.kind.rawValue)")
3185
3186            guard preview.kind == expectedKind else {
3187                let message = preview.kind == .backup
3188                    ? "That file is a full backup. Use Import Backup."
3189                    : "That file type does not match this import action."
3190                DomainDebugLog.error("DataPortabilitySettingsView.handleImportResult kindMismatch message=\(message)")
3191                recordImportDebugStatus("Kind mismatch: \(message)")
3192                presentImportError(message)
3193                return
3194            }
3195
3196            DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult presentingPreview kind=\(preview.kind.rawValue)")
3197            recordImportDebugStatus("Presenting preview for \(preview.kind.rawValue)")
3198            presentImportPreview(preview)
3199        } catch {
3200            DomainDebugLog.error("DataPortabilitySettingsView.handleImportResult failed error=\(error.localizedDescription)")
3201            recordImportDebugStatus("Import failed: \(error.localizedDescription)")
3202            presentImportError(error.localizedDescription)
3203        }
3204    }
3205
3206    private func applyPendingImport() {
3207        guard let pendingImportPreview else { return }
3208        do {
3209            _ = try viewModel.applyDataImport(pendingImportPreview, mode: importMode)
3210            self.pendingImportPreview = nil
3211        } catch {
3212            pendingImportError = error.localizedDescription
3213        }
3214    }
3215
3216    private func portabilityFilename(suffix: String, fileExtension: String) -> String {
3217        let formatter = DateFormatter()
3218        formatter.dateFormat = "yyyyMMdd_HHmmss"
3219        return "\(formatter.string(from: Date()))_domaindig_\(suffix).\(fileExtension)"
3220    }
3221
3222    private func presentImportPreview(_ preview: DataImportPreview) {
3223        Task { @MainActor in
3224            try? await Task.sleep(for: .milliseconds(300))
3225            DomainDebugLog.debug("DataPortabilitySettingsView.presentImportPreview kind=\(preview.kind.rawValue) fileName=\(preview.fileName)")
3226            recordImportDebugStatus("Preview presented for \(preview.fileName)")
3227            pendingImportPreview = preview
3228        }
3229    }
3230
3231    private func presentImportError(_ message: String) {
3232        Task { @MainActor in
3233            try? await Task.sleep(for: .milliseconds(300))
3234            DomainDebugLog.error("DataPortabilitySettingsView.presentImportError message=\(message)")
3235            recordImportDebugStatus("Error presented: \(message)")
3236            pendingImportError = message
3237        }
3238    }
3239
3240    private func recordImportDebugStatus(_ message: String) {
3241        #if DEBUG
3242        let status = "[Import Debug] \(message)"
3243        importDebugStatus = status
3244        print(status)
3245        #endif
3246    }
3247}
3248
3249private struct DataManagementSettingsView: View {
3250    @Bindable var viewModel: DomainViewModel
3251
3252    @State private var showClearHistoryConfirmation = false
3253    @State private var showClearCacheConfirmation = false
3254    @State private var showClearWorkflowsConfirmation = false
3255    @State private var showClearTrackedDomainsConfirmation = false
3256
3257    var body: some View {
3258        Form {
3259            Section("Data") {
3260                Button("Clear History", role: .destructive) {
3261                    showClearHistoryConfirmation = true
3262                }
3263
3264                Button("Clear Cache", role: .destructive) {
3265                    showClearCacheConfirmation = true
3266                }
3267
3268                Button("Clear Workflows", role: .destructive) {
3269                    showClearWorkflowsConfirmation = true
3270                }
3271
3272                Button("Clear Tracked Domains", role: .destructive) {
3273                    showClearTrackedDomainsConfirmation = true
3274                }
3275            }
3276        }
3277        .navigationTitle("Data Management")
3278        .alert("Clear history?", isPresented: $showClearHistoryConfirmation) {
3279            Button("Clear", role: .destructive) {
3280                viewModel.clearHistory()
3281            }
3282            Button("Cancel", role: .cancel) {}
3283        } message: {
3284            Text("This removes saved lookup snapshots and clears monitoring run history on this device.")
3285        }
3286        .alert("Clear cache?", isPresented: $showClearCacheConfirmation) {
3287            Button("Clear", role: .destructive) {
3288                viewModel.clearLookupCache()
3289            }
3290            Button("Cancel", role: .cancel) {}
3291        } message: {
3292            Text("This clears the in-memory lookup cache and cancels any cached in-flight work.")
3293        }
3294        .alert("Clear workflows?", isPresented: $showClearWorkflowsConfirmation) {
3295            Button("Clear", role: .destructive) {
3296                viewModel.clearWorkflows()
3297            }
3298            Button("Cancel", role: .cancel) {}
3299        } message: {
3300            Text("This removes saved workflows only. History, tracked domains, and saved reports stay intact.")
3301        }
3302        .alert("Clear tracked domains?", isPresented: $showClearTrackedDomainsConfirmation) {
3303            Button("Clear", role: .destructive) {
3304                viewModel.clearTrackedDomains()
3305            }
3306            Button("Cancel", role: .cancel) {}
3307        } message: {
3308            Text("This removes the watchlist and clears monitoring run history. History and workflows stay intact.")
3309        }
3310    }
3311}
3312
3313private struct AboutSettingsView: View {
3314    @State private var cloudSyncService = CloudSyncService.shared
3315
3316    private var appVersion: String {
3317        AppVersion.current
3318    }
3319
3320    var body: some View {
3321        Form {
3322            Section("About") {
3323                LabeledContent("Version", value: appVersion)
3324                LabeledContent("Storage", value: cloudSyncService.isEnabled ? "Local-first + iCloud" : "Local-only")
3325                LabeledContent("Backup Schema", value: "v\(DomainDigBackup.currentSchemaVersion)")
3326            }
3327        }
3328        .navigationTitle("App Info")
3329        .task {
3330            await cloudSyncService.refreshAvailability()
3331        }
3332    }
3333}
3334
3335private struct DataImportPreviewSheet: View {
3336    @Environment(\.dismiss) private var dismiss
3337
3338    let preview: DataImportPreview
3339    let mode: DataPortabilityImportMode
3340    let onCancel: () -> Void
3341    let onApply: () -> Void
3342
3343    var body: some View {
3344        NavigationStack {
3345            List {
3346                Section("Summary") {
3347                    ForEach(preview.summaryLines, id: \.self) { line in
3348                        Text(line)
3349                    }
3350                }
3351
3352                Section("Projected Counts") {
3353                    LabeledContent("Tracked Domains", value: "\(preview.projectedCounts.trackedDomains)")
3354                    LabeledContent("History Snapshots", value: "\(preview.projectedCounts.historySnapshots)")
3355                    LabeledContent("Workflows", value: "\(preview.projectedCounts.workflows)")
3356                    LabeledContent("Cached Items", value: "\(preview.projectedCounts.cachedItems)")
3357                    LabeledContent("Monitoring Logs", value: "\(preview.projectedCounts.monitoringLogs)")
3358                }
3359
3360                if !preview.warnings.isEmpty {
3361                    Section("Warnings") {
3362                        ForEach(preview.warnings, id: \.self) { warning in
3363                            Text(warning)
3364                                .foregroundStyle(.secondary)
3365                        }
3366                    }
3367                }
3368            }
3369            .navigationTitle("Import Preview")
3370            .toolbar {
3371                ToolbarItem(placement: .cancellationAction) {
3372                    Button("Cancel") {
3373                        onCancel()
3374                        dismiss()
3375                    }
3376                }
3377                ToolbarItem(placement: .confirmationAction) {
3378                    Button(mode == .replace ? "Replace" : "Import") {
3379                        onApply()
3380                        if mode == .merge {
3381                            dismiss()
3382                        }
3383                    }
3384                }
3385            }
3386        }
3387    }
3388}
3389
3390#Preview {
3391    ContentView(viewModel: DomainViewModel())
3392}