DomainDig/SettingsViews.swift

1128 lines · 46617 bytes

   1import SwiftUI
   2import UniformTypeIdentifiers
   3
   4// Settings screens extracted from ContentView.swift. `SettingsView` is the
   5// Settings tab root (presented from RootTabView); the per-section screens are
   6// file-private, reached only through its navigation links.
   7
   8struct SettingsView: View {
   9    @Environment(\.appDensity) private var appDensity
  10    @Bindable var viewModel: DomainViewModel
  11    @State private var purchaseService = PurchaseService.shared
  12
  13    var body: some View {
  14
  15        List {
  16            Section("Tier") {
  17                LabeledContent("Status", value: purchaseService.currentTier.title)
  18
  19                if purchaseService.currentTier == .free {
  20                    Button("Upgrade") {
  21                        viewModel.isPaywallPresented = true
  22                    }
  23                } else {
  24                    Button("Manage Subscription") {
  25                        Task {
  26                            await purchaseService.manageSubscription()
  27                        }
  28                    }
  29                }
  30
  31                Button(purchaseService.isRestoring ? "Restoring…" : "Restore Purchases") {
  32                    Task {
  33                        await purchaseService.restorePurchases()
  34                    }
  35                }
  36                .disabled(purchaseService.isRestoring || purchaseService.isPurchasing)
  37
  38                if let statusMessage = purchaseService.statusMessage {
  39                    Text(statusMessage)
  40                        .font(appDensity.font(.caption, design: .default))
  41                        .foregroundStyle(Color(.appTextSecondary))
  42                }
  43
  44                if let errorMessage = purchaseService.errorMessage {
  45                    Text(errorMessage)
  46                        .font(appDensity.font(.caption, design: .default))
  47                        .foregroundStyle(Color(.statusCritical))
  48                }
  49            }
  50
  51            Section("Preferences") {
  52                NavigationLink("Display") {
  53                    DisplaySettingsView()
  54                }
  55
  56                NavigationLink("History & Network") {
  57                    HistoryNetworkSettingsView(viewModel: viewModel)
  58                }
  59            }
  60
  61            Section("Services") {
  62                NavigationLink("Monitoring Log") {
  63                    MonitoringView(viewModel: viewModel)
  64                }
  65
  66                NavigationLink("Integrations") {
  67                    IntegrationsSettingsView()
  68                }
  69
  70                NavigationLink("Local API") {
  71                    LocalAPISettingsView()
  72                }
  73
  74                NavigationLink("iCloud Sync") {
  75                    CloudSyncSettingsView()
  76                }
  77
  78                NavigationLink("Monitoring Settings") {
  79                    MonitoringSettingsView(viewModel: viewModel)
  80                }
  81
  82                NavigationLink("Scheduled Reports") {
  83                    ScheduledReportsView()
  84                }
  85            }
  86
  87            Section("Data") {
  88                NavigationLink("Import & Export") {
  89                    DataPortabilitySettingsView(viewModel: viewModel)
  90                }
  91
  92                NavigationLink("Data Management") {
  93                    DataManagementSettingsView(viewModel: viewModel)
  94                }
  95            }
  96
  97            Section("About") {
  98                NavigationLink("App Info") {
  99                    AppInfoView()
 100                }
 101            }
 102        }
 103        .navigationTitle("Settings")
 104    }
 105}
 106
 107private struct DisplaySettingsView: View {
 108    @AppStorage(AppDensity.userDefaultsKey) private var storedDensity = AppDensity.compact.rawValue
 109    @AppStorage(AppAppearance.userDefaultsKey) private var storedAppearance = AppAppearance.system.rawValue
 110
 111    var body: some View {
 112        Form {
 113            Section("Display") {
 114                Picker("Appearance", selection: $storedAppearance) {
 115                    ForEach(AppAppearance.allCases) { appearance in
 116                        Text(appearance.title).tag(appearance.rawValue)
 117                    }
 118                }
 119
 120                Picker("Density", selection: $storedDensity) {
 121                    ForEach(AppDensity.allCases) { density in
 122                        Text(density.title).tag(density.rawValue)
 123                    }
 124                }
 125            }
 126        }
 127        .navigationTitle("Display")
 128    }
 129}
 130
 131private struct HistoryNetworkSettingsView: View {
 132    @Environment(\.appDensity) private var appDensity
 133    @Bindable var viewModel: DomainViewModel
 134    @AppStorage(DNSResolverOption.userDefaultsKey) private var storedResolverURL = DNSResolverOption.defaultURLString
 135    @AppStorage(AppDensity.userDefaultsKey) private var storedDensity = AppDensity.compact.rawValue
 136    @AppStorage(InspectionScope.profileDefaultsKey) private var storedProfile = InspectionProfile.full.rawValue
 137    @AppStorage(InspectionScope.enrichmentDefaultsKey) private var allowsThirdPartyEnrichment = true
 138
 139    @State private var resolverOption: DNSResolverOption = .cloudflare
 140    @State private var customResolverURL = DNSResolverOption.defaultURLString
 141
 142    private static let enrichmentCaption = """
 143        On, DomainDig asks rdap.org for registration and ownership, crt.sh for subdomain discovery, \
 144        and ipapi.co for IP location. Off, it contacts none of them: ownership, subdomain discovery, \
 145        IP location and name suggestions become unavailable, and registration is decided from DNS \
 146        alone, so a domain that resolves reads as registered and anything else as unknown.
 147        """
 148
 149    private var selectedProfile: InspectionProfile {
 150        InspectionProfile(rawValue: storedProfile) ?? .full
 151    }
 152
 153    private var customResolverError: String? {
 154        guard resolverOption == .custom else { return nil }
 155        return DNSResolverOption.isValidCustomURL(customResolverURL) ? nil : "Resolver URL must start with https://"
 156    }
 157
 158    var body: some View {
 159        Form {
 160            Section("History") {
 161                Picker(
 162                    "Auto-prune",
 163                    selection: Binding(
 164                        get: { viewModel.historyAutoPruneOption },
 165                        set: { viewModel.setHistoryAutoPruneOption($0) }
 166                    )
 167                ) {
 168                    ForEach(HistoryAutoPruneOption.allCases) { option in
 169                        Text(option.title).tag(option)
 170                    }
 171                }
 172
 173                Text(viewModel.historyRetentionCaption)
 174                    .font(appDensity.font(.caption, design: .default))
 175                    .foregroundStyle(Color(.appTextSecondary))
 176            }
 177
 178            Section("Network") {
 179                Picker("Resolver", selection: $resolverOption) {
 180                    ForEach(DNSResolverOption.allCases) { option in
 181                        Text(option.title).tag(option)
 182                    }
 183                }
 184
 185                if resolverOption == .custom {
 186                    TextField("https://resolver.example/dns-query", text: $customResolverURL)
 187                        .textInputAutocapitalization(.never)
 188                        .autocorrectionDisabled()
 189                        .keyboardType(.URL)
 190
 191                    if let customResolverError {
 192                        Text(customResolverError)
 193                            .font(appDensity.font(.caption, design: .default))
 194                            .foregroundStyle(Color(.statusCritical))
 195                    }
 196                }
 197
 198                Picker("Lookup profile", selection: $storedProfile) {
 199                    ForEach(InspectionProfile.allCases) { profile in
 200                        Text(profile.title).tag(profile.rawValue)
 201                    }
 202                }
 203
 204                Text(selectedProfile.detail)
 205                    .font(appDensity.font(.caption, design: .default))
 206                    .foregroundStyle(Color(.appTextSecondary))
 207
 208                Toggle("Allow third-party enrichment", isOn: $allowsThirdPartyEnrichment)
 209
 210                Text(Self.enrichmentCaption)
 211                    .font(appDensity.font(.caption, design: .default))
 212                    .foregroundStyle(Color(.appTextSecondary))
 213            }
 214        }
 215        .navigationTitle("History & Network")
 216        .onAppear {
 217            let currentResolverURL = storedResolverURL.trimmingCharacters(in: .whitespacesAndNewlines)
 218            resolverOption = DNSResolverOption.option(for: currentResolverURL)
 219            customResolverURL = resolverOption == .custom ? currentResolverURL : DNSResolverOption.defaultURLString
 220        }
 221        .onChange(of: resolverOption) { _, newValue in
 222            guard let presetURL = newValue.urlString else {
 223                storedResolverURL = customResolverURL.trimmingCharacters(in: .whitespacesAndNewlines)
 224                viewModel.persistCurrentAppSettings(
 225                    resolverURLString: storedResolverURL,
 226                    appDensityRawValue: storedDensity
 227                )
 228                return
 229            }
 230            storedResolverURL = presetURL
 231            viewModel.persistCurrentAppSettings(
 232                resolverURLString: storedResolverURL,
 233                appDensityRawValue: storedDensity
 234            )
 235        }
 236        .onChange(of: customResolverURL) { _, newValue in
 237            guard resolverOption == .custom else { return }
 238            storedResolverURL = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
 239            viewModel.persistCurrentAppSettings(
 240                resolverURLString: storedResolverURL,
 241                appDensityRawValue: storedDensity
 242            )
 243        }
 244        .onChange(of: storedDensity) { _, newValue in
 245            viewModel.persistCurrentAppSettings(
 246                resolverURLString: storedResolverURL,
 247                appDensityRawValue: newValue
 248            )
 249        }
 250    }
 251}
 252
 253private struct CloudSyncSettingsView: View {
 254    @Environment(\.appDensity) private var appDensity
 255    @State private var cloudSyncService = CloudSyncService.shared
 256
 257    var body: some View {
 258        Form {
 259            Section("iCloud Sync") {
 260                Toggle(
 261                    "Enable iCloud Sync",
 262                    isOn: Binding(
 263                        get: { cloudSyncService.isEnabled },
 264                        set: { cloudSyncService.setSyncEnabled($0) }
 265                    )
 266                )
 267
 268                LabeledContent("Status", value: cloudSyncService.status.title)
 269                LabeledContent(
 270                    "Last Sync",
 271                    value: cloudSyncService.lastSyncDate?.formatted(date: .abbreviated, time: .shortened) ?? "Not yet synced"
 272                )
 273
 274                Button(cloudSyncService.status == .syncing ? "Syncing…" : "Sync Now") {
 275                    Task {
 276                        await cloudSyncService.syncNow(trigger: .manual)
 277                    }
 278                }
 279                .disabled(!cloudSyncService.isEnabled || cloudSyncService.status == .syncing)
 280
 281                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.")
 282                    .font(appDensity.font(.caption, design: .default))
 283                    .foregroundStyle(Color(.appTextSecondary))
 284
 285                Text(cloudSyncService.detailMessage)
 286                    .font(appDensity.font(.caption, design: .default))
 287                    .foregroundStyle(Color(.appTextSecondary))
 288
 289                if let lastErrorMessage = cloudSyncService.lastErrorMessage {
 290                    Text(lastErrorMessage)
 291                        .font(appDensity.font(.caption, design: .default))
 292                        .foregroundStyle(Color(.statusCritical))
 293                }
 294            }
 295        }
 296        .navigationTitle("iCloud Sync")
 297        .task {
 298            await cloudSyncService.refreshAvailability()
 299        }
 300    }
 301}
 302
 303private struct LocalAPISettingsView: View {
 304    @Environment(\.appDensity) private var appDensity
 305    @State private var localAPIService = LocalAPIService.shared
 306    @State private var portText = ""
 307
 308    private var statusText: String {
 309        if localAPIService.isRunning { return "Running" }
 310        return localAPIService.config.isEnabled ? "Stopped" : "Disabled"
 311    }
 312
 313    var body: some View {
 314        Form {
 315            Section("Local API") {
 316                Toggle(
 317                    "Enable Local API",
 318                    isOn: Binding(
 319                        get: { localAPIService.config.isEnabled },
 320                        set: { localAPIService.setEnabled($0) }
 321                    )
 322                )
 323
 324                TextField(
 325                    "Port",
 326                    text: Binding(
 327                        get: { portText },
 328                        set: { newValue in
 329                            portText = newValue
 330                            if let port = Int(newValue) {
 331                                localAPIService.setPort(port)
 332                            }
 333                        }
 334                    )
 335                )
 336                .keyboardType(.numberPad)
 337
 338                LabeledContent("Address", value: localAPIService.address)
 339                LabeledContent("Status", value: statusText)
 340                LabeledContent("Token", value: localAPIService.maskedToken)
 341
 342                if let statusMessage = localAPIService.statusMessage {
 343                    Text(statusMessage)
 344                        .font(appDensity.font(.caption, design: .default))
 345                        .foregroundStyle(Color(.appTextSecondary))
 346                }
 347            }
 348
 349            Section("Authentication") {
 350                Button("Copy Token") {
 351                    localAPIService.copyToken()
 352                }
 353
 354                Button("Copy cURL Command") {
 355                    localAPIService.copyCurlCommand()
 356                }
 357
 358                Button("Rotate Token") {
 359                    localAPIService.rotateToken()
 360                }
 361
 362                Text("Every request requires either `Authorization: Bearer <token>` or `X-API-Token`. DomainDig stores the token in Keychain and only binds the server to localhost.")
 363                    .font(appDensity.font(.caption, design: .default))
 364                    .foregroundStyle(Color(.appTextSecondary))
 365            }
 366
 367            Section("Request Logging") {
 368                Toggle(
 369                    "Log Requests",
 370                    isOn: Binding(
 371                        get: { localAPIService.config.requestLoggingEnabled },
 372                        set: { localAPIService.setRequestLoggingEnabled($0) }
 373                    )
 374                )
 375
 376                if localAPIService.requestLogs.isEmpty {
 377                    Text("No local API requests logged yet.")
 378                        .font(appDensity.font(.caption, design: .default))
 379                        .foregroundStyle(Color(.appTextSecondary))
 380                } else {
 381                    ForEach(localAPIService.requestLogs.prefix(25)) { log in
 382                        VStack(alignment: .leading, spacing: 4) {
 383                            HStack {
 384                                Text("\(log.method) \(log.path)")
 385                                    .font(appDensity.font(.callout, design: .monospaced))
 386                                Spacer()
 387                                Text("\(log.statusCode)")
 388                                    .font(appDensity.font(.caption, design: .default))
 389                                    .foregroundStyle(log.statusCode >= 400 ? Color(.statusCritical) : .secondary)
 390                            }
 391
 392                            Text(log.timestamp.formatted(date: .abbreviated, time: .standard))
 393                                .font(appDensity.font(.caption2, design: .default))
 394                                .foregroundStyle(Color(.appTextSecondary))
 395
 396                            Text("\(Int(log.duration * 1000)) ms")
 397                                .font(appDensity.font(.caption2, design: .default))
 398                                .foregroundStyle(Color(.appTextSecondary))
 399                        }
 400                    }
 401                }
 402
 403                Button("Clear Logs", role: .destructive) {
 404                    localAPIService.clearRequestLogs()
 405                }
 406            }
 407
 408            Section("Control") {
 409                Button("Restart Server") {
 410                    localAPIService.setEnabled(false)
 411                    localAPIService.setEnabled(true)
 412                }
 413                .disabled(!localAPIService.config.isEnabled)
 414
 415                Button("Stop Server") {
 416                    localAPIService.stopServer()
 417                }
 418                .disabled(!localAPIService.isRunning)
 419            }
 420        }
 421        .navigationTitle("Local API")
 422        .onAppear {
 423            portText = String(localAPIService.config.port)
 424            localAPIService.refresh()
 425        }
 426    }
 427}
 428
 429private struct MonitoringSettingsView: View {
 430    @Environment(\.appDensity) private var appDensity
 431    @Bindable var viewModel: DomainViewModel
 432
 433    private var notificationAuthorizationLabel: String {
 434        switch viewModel.monitoringNotificationStatus {
 435        case .authorized, .provisional, .ephemeral:
 436            return "Allowed"
 437        case .denied:
 438            return "Denied"
 439        case .notDetermined:
 440            return "Not Requested"
 441        @unknown default:
 442            return "Unknown"
 443        }
 444    }
 445
 446    var body: some View {
 447        Form {
 448            Section("Monitoring") {
 449                Toggle(
 450                    "Enable Background Monitoring",
 451                    isOn: Binding(
 452                        get: { viewModel.monitoringSettings.isEnabled },
 453                        set: { viewModel.setMonitoringEnabled($0) }
 454                    )
 455                )
 456
 457                Picker(
 458                    "Base Interval",
 459                    selection: Binding(
 460                        get: { MonitoringBaseInterval.nearest(to: viewModel.monitoringSettings.baseInterval) },
 461                        set: { viewModel.setMonitoringBaseInterval($0) }
 462                    )
 463                ) {
 464                    ForEach(MonitoringBaseInterval.allCases) { interval in
 465                        Text(interval.title).tag(interval)
 466                    }
 467                }
 468
 469                Toggle(
 470                    "Adaptive Monitoring",
 471                    isOn: Binding(
 472                        get: { viewModel.monitoringSettings.adaptiveEnabled },
 473                        set: { viewModel.setMonitoringAdaptiveEnabled($0) }
 474                    )
 475                )
 476
 477                Picker(
 478                    "Sensitivity",
 479                    selection: Binding(
 480                        get: { viewModel.monitoringSettings.sensitivity },
 481                        set: { viewModel.setMonitoringSensitivity($0) }
 482                    )
 483                ) {
 484                    ForEach(MonitoringSensitivity.allCases) { sensitivity in
 485                        Text(sensitivity.title).tag(sensitivity)
 486                    }
 487                }
 488
 489                let quietHoursStart = viewModel.monitoringSettings.quietHours?.startHour ?? 22
 490                let quietHoursEnd = viewModel.monitoringSettings.quietHours?.endHour ?? 7
 491                Toggle(
 492                    "Quiet Hours",
 493                    isOn: Binding(
 494                        get: { viewModel.monitoringSettings.quietHours != nil },
 495                        set: { isEnabled in
 496                            viewModel.setMonitoringQuietHours(
 497                                startHour: quietHoursStart,
 498                                endHour: quietHoursEnd,
 499                                isEnabled: isEnabled
 500                            )
 501                        }
 502                    )
 503                )
 504
 505                if viewModel.monitoringSettings.quietHours != nil {
 506                    hourPicker("Quiet Starts", selection: Binding(
 507                        get: { quietHoursStart },
 508                        set: { viewModel.setMonitoringQuietHours(startHour: $0, endHour: quietHoursEnd, isEnabled: true) }
 509                    ))
 510                    hourPicker("Quiet Ends", selection: Binding(
 511                        get: { quietHoursEnd },
 512                        set: { viewModel.setMonitoringQuietHours(startHour: quietHoursStart, endHour: $0, isEnabled: true) }
 513                    ))
 514                }
 515
 516                Picker(
 517                    "Domains",
 518                    selection: Binding(
 519                        get: { viewModel.monitoringSettings.scope },
 520                        set: { viewModel.setMonitoringScope($0) }
 521                    )
 522                ) {
 523                    ForEach(MonitoringScope.allCases) { scope in
 524                        Text(scope.title).tag(scope)
 525                    }
 526                }
 527
 528                if viewModel.monitoringSettings.scope == .selectedOnly {
 529                    ForEach(viewModel.trackedDomains) { trackedDomain in
 530                        Toggle(
 531                            trackedDomain.domain,
 532                            isOn: Binding(
 533                                get: { viewModel.monitoringSettings.selectedDomainIDs.contains(trackedDomain.id) },
 534                                set: { viewModel.setMonitoringSelection(for: trackedDomain, isSelected: $0) }
 535                            )
 536                        )
 537                    }
 538                }
 539
 540                Toggle(
 541                    "Local Alerts",
 542                    isOn: Binding(
 543                        get: { viewModel.monitoringSettings.alertsEnabled },
 544                        set: { isEnabled in
 545                            if isEnabled {
 546                                Task {
 547                                    await viewModel.requestMonitoringNotificationAuthorization()
 548                                }
 549                            } else {
 550                                viewModel.setMonitoringAlertsEnabled(false)
 551                            }
 552                        }
 553                    )
 554                )
 555
 556                Picker(
 557                    "Notify For",
 558                    selection: Binding(
 559                        get: { viewModel.monitoringSettings.alertFilter },
 560                        set: { viewModel.setMonitoringAlertFilter($0) }
 561                    )
 562                ) {
 563                    ForEach(MonitoringAlertFilter.allCases) { filter in
 564                        Text(filter.title).tag(filter)
 565                    }
 566                }
 567
 568                LabeledContent("Background Refresh", value: DomainMonitoringScheduler.shared.backgroundRefreshStatusDescription())
 569                LabeledContent("Notification Access", value: notificationAuthorizationLabel)
 570
 571                if let monitoringStatusMessage = viewModel.monitoringStatusMessage {
 572                    Text(monitoringStatusMessage)
 573                        .font(appDensity.font(.caption, design: .default))
 574                        .foregroundStyle(Color(.appTextSecondary))
 575                }
 576
 577                if !FeatureAccessService.hasAccess(to: .automatedMonitoring) {
 578                    Text("Background monitoring and alerts are available in Pro.")
 579                        .font(appDensity.font(.caption, design: .default))
 580                        .foregroundStyle(Color(.appTextSecondary))
 581                }
 582            }
 583        }
 584        .navigationTitle("Monitoring")
 585        .onAppear {
 586            viewModel.refreshMonitoringState()
 587            Task {
 588                await viewModel.refreshMonitoringAuthorizationStatus()
 589            }
 590        }
 591    }
 592
 593    private func hourPicker(_ title: String, selection: Binding<Int>) -> some View {
 594        Picker(title, selection: selection) {
 595            ForEach(0..<24, id: \.self) { hour in
 596                Text(Self.monitoringHourLabel(for: hour)).tag(hour)
 597            }
 598        }
 599    }
 600
 601    private static func monitoringHourLabel(for hour: Int) -> String {
 602        let formatter = DateFormatter()
 603        formatter.dateFormat = "h a"
 604        let components = DateComponents(calendar: .current, hour: hour)
 605        return components.date.map(formatter.string(from:)) ?? "\(hour):00"
 606    }
 607}
 608
 609private struct DataPortabilitySettingsView: View {
 610    private enum ImportTarget {
 611        case backup
 612        case trackedDomains
 613        case workflows
 614
 615        var expectedKind: DataPortabilityImportKind {
 616            switch self {
 617            case .backup:
 618                return .backup
 619            case .trackedDomains:
 620                return .trackedDomains
 621            case .workflows:
 622                return .workflows
 623            }
 624        }
 625
 626        var allowedContentTypes: [UTType] {
 627            switch self {
 628            case .backup:
 629                return [UTType.json]
 630            case .trackedDomains, .workflows:
 631                return [UTType.json, UTType.commaSeparatedText]
 632            }
 633        }
 634    }
 635
 636    @Environment(\.appDensity) private var appDensity
 637    @Bindable var viewModel: DomainViewModel
 638
 639    @State private var importMode: DataPortabilityImportMode = .merge
 640    @State private var activeImportTarget: ImportTarget?
 641    @State private var pendingImportTarget: ImportTarget?
 642    @State private var importDebugStatus: String?
 643    @State private var pendingImportPreview: DataImportPreview?
 644    @State private var pendingImportError: String?
 645    @State private var showReplaceImportConfirmation = false
 646
 647    var body: some View {
 648        Form {
 649            Section("Import & Export") {
 650                Picker("Import Mode", selection: $importMode) {
 651                    ForEach(DataPortabilityImportMode.allCases) { mode in
 652                        Text(mode.title).tag(mode)
 653                    }
 654                }
 655
 656                Text(importMode.explanation)
 657                    .font(appDensity.font(.caption, design: .default))
 658                    .foregroundStyle(Color(.appTextSecondary))
 659
 660                Button("Export Full Backup") {
 661                    exportFullBackup()
 662                }
 663
 664                Button("Import Backup") {
 665                    recordImportDebugStatus("Tapped Import Backup")
 666                    pendingImportTarget = .backup
 667                    activeImportTarget = .backup
 668                }
 669
 670                Menu("Export Tracked Domains") {
 671                    Button("JSON") {
 672                        exportPortableTrackedDomainsJSON()
 673                    }
 674                    Button("CSV") {
 675                        exportPortableTrackedDomainsCSV()
 676                    }
 677                }
 678
 679                Button("Import Tracked Domains") {
 680                    recordImportDebugStatus("Tapped Import Tracked Domains")
 681                    pendingImportTarget = .trackedDomains
 682                    activeImportTarget = .trackedDomains
 683                }
 684
 685                Menu("Export Workflows") {
 686                    Button("JSON") {
 687                        exportPortableWorkflowsJSON()
 688                    }
 689                    Button("CSV") {
 690                        exportPortableWorkflowsCSV()
 691                    }
 692                }
 693
 694                Button("Import Workflows") {
 695                    recordImportDebugStatus("Tapped Import Workflows")
 696                    pendingImportTarget = .workflows
 697                    activeImportTarget = .workflows
 698                }
 699
 700                Button("Export History") {
 701                    exportPortableHistoryJSON()
 702                }
 703            }
 704
 705            Section("Local Data") {
 706                LabeledContent("Tracked Domains", value: "\(viewModel.dataLifecycleSummary.trackedDomains)")
 707                LabeledContent("History Snapshots", value: "\(viewModel.dataLifecycleSummary.historySnapshots)")
 708                LabeledContent("Audit Sessions", value: "\(viewModel.dataLifecycleSummary.auditSessions)")
 709                LabeledContent("Workflows", value: "\(viewModel.dataLifecycleSummary.workflows)")
 710                LabeledContent("Cached Items", value: "\(viewModel.dataLifecycleSummary.cachedItems)")
 711                LabeledContent("Monitoring Logs", value: "\(viewModel.dataLifecycleSummary.monitoringLogs)")
 712
 713                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.")
 714                    .font(appDensity.font(.caption, design: .default))
 715                    .foregroundStyle(Color(.appTextSecondary))
 716
 717                if let portabilityStatusMessage = viewModel.portabilityStatusMessage {
 718                    Text(portabilityStatusMessage)
 719                        .font(appDensity.font(.caption, design: .default))
 720                        .foregroundStyle(Color(.appTextSecondary))
 721                }
 722            }
 723
 724            #if DEBUG
 725            if let importDebugStatus {
 726                Section("Import Debug") {
 727                    Text(importDebugStatus)
 728                        .font(appDensity.font(.caption, design: .default))
 729                        .foregroundStyle(Color(.appTextSecondary))
 730                        .textSelection(.enabled)
 731                }
 732            }
 733            #endif
 734        }
 735        .navigationTitle("Import & Export")
 736        .alert("Replace local data?", isPresented: $showReplaceImportConfirmation) {
 737            Button("Replace", role: .destructive) {
 738                applyPendingImport()
 739            }
 740            Button("Cancel", role: .cancel) { /* Dismiss only; SwiftUI closes the alert. */ }
 741        } message: {
 742            Text("Replace mode overwrites local data covered by the imported file and may remove items that are only on this device.")
 743        }
 744        .alert("Import Error", isPresented: Binding(
 745            get: { pendingImportError != nil },
 746            set: { if !$0 { pendingImportError = nil } }
 747        )) {
 748            Button("OK", role: .cancel) { /* Dismiss only; SwiftUI closes the alert. */ }
 749        } message: {
 750            Text(pendingImportError ?? "The import could not be completed.")
 751        }
 752        .sheet(isPresented: Binding(
 753            get: { pendingImportPreview != nil },
 754            set: { if !$0 { pendingImportPreview = nil } }
 755        )) {
 756            if let pendingImportPreview {
 757                DataImportPreviewSheet(
 758                    preview: pendingImportPreview,
 759                    mode: importMode,
 760                    onCancel: {
 761                        self.pendingImportPreview = nil
 762                    },
 763                    onApply: {
 764                        if importMode == .replace {
 765                            showReplaceImportConfirmation = true
 766                        } else {
 767                            applyPendingImport()
 768                        }
 769                    }
 770                )
 771            }
 772        }
 773        .fileImporter(
 774            isPresented: Binding(
 775                get: { activeImportTarget != nil },
 776                set: { if !$0 { activeImportTarget = nil } }
 777            ),
 778            allowedContentTypes: activeImportTarget?.allowedContentTypes ?? [UTType.json],
 779            allowsMultipleSelection: false
 780        ) { result in
 781            guard let pendingImportTarget else {
 782                recordImportDebugStatus("fileImporter returned with no active target")
 783                return
 784            }
 785            recordImportDebugStatus("fileImporter returned for \(pendingImportTarget.expectedKind.rawValue)")
 786            handleImportResult(result, expectedKind: pendingImportTarget.expectedKind)
 787            self.pendingImportTarget = nil
 788            self.activeImportTarget = nil
 789        }
 790        .onAppear {
 791            viewModel.refreshDataLifecycleSummary()
 792        }
 793    }
 794
 795    private func exportFullBackup() {
 796        guard let data = viewModel.exportFullBackupData() else { return }
 797        ExportPresenter.share(filename: portabilityFilename(suffix: "backup", fileExtension: "json"), data: data)
 798    }
 799
 800    private func exportPortableTrackedDomainsJSON() {
 801        guard let data = viewModel.exportPortableTrackedDomainsJSONData() else { return }
 802        ExportPresenter.share(filename: portabilityFilename(suffix: "tracked_domains", fileExtension: "json"), data: data)
 803    }
 804
 805    private func exportPortableTrackedDomainsCSV() {
 806        ExportPresenter.share(
 807            filename: portabilityFilename(suffix: "tracked_domains", fileExtension: "csv"),
 808            contents: viewModel.exportPortableTrackedDomainsCSV()
 809        )
 810    }
 811
 812    private func exportPortableWorkflowsJSON() {
 813        guard let data = viewModel.exportPortableWorkflowsJSONData() else { return }
 814        ExportPresenter.share(filename: portabilityFilename(suffix: "workflows", fileExtension: "json"), data: data)
 815    }
 816
 817    private func exportPortableWorkflowsCSV() {
 818        ExportPresenter.share(
 819            filename: portabilityFilename(suffix: "workflows", fileExtension: "csv"),
 820            contents: viewModel.exportPortableWorkflowsCSV()
 821        )
 822    }
 823
 824    private func exportPortableHistoryJSON() {
 825        guard let data = viewModel.exportPortableHistoryJSONData() else { return }
 826        ExportPresenter.share(filename: portabilityFilename(suffix: "history", fileExtension: "json"), data: data)
 827    }
 828
 829    private func handleImportResult(
 830        _ result: Result<[URL], Error>,
 831        expectedKind: DataPortabilityImportKind
 832    ) {
 833        DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult expectedKind=\(expectedKind.rawValue)")
 834        recordImportDebugStatus("handleImportResult started for \(expectedKind.rawValue)")
 835        do {
 836            let urls = try result.get()
 837            guard let url = urls.first else {
 838                DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult noURLReturned")
 839                recordImportDebugStatus("No URL returned from picker")
 840                return
 841            }
 842            DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult selectedURL=\(url.absoluteString)")
 843            recordImportDebugStatus("Selected \(url.lastPathComponent)")
 844            let shouldStopAccessing = url.startAccessingSecurityScopedResource()
 845            DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult securityScopeGranted=\(shouldStopAccessing)")
 846            recordImportDebugStatus("Security scope granted: \(shouldStopAccessing)")
 847            defer {
 848                if shouldStopAccessing {
 849                    url.stopAccessingSecurityScopedResource()
 850                    DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult securityScopeReleased")
 851                }
 852            }
 853
 854            let data = try Data(contentsOf: url)
 855            DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult dataRead bytes=\(data.count) fileName=\(url.lastPathComponent)")
 856            recordImportDebugStatus("Read \(data.count) bytes from \(url.lastPathComponent)")
 857            let preview = try viewModel.prepareDataImport(
 858                data: data,
 859                fileName: url.lastPathComponent,
 860                mode: importMode
 861            )
 862            DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult previewReady previewKind=\(preview.kind.rawValue) expectedKind=\(expectedKind.rawValue)")
 863            recordImportDebugStatus("Preview ready: \(preview.kind.rawValue)")
 864
 865            guard preview.kind == expectedKind else {
 866                let message = preview.kind == .backup
 867                    ? "That file is a full backup. Use Import Backup."
 868                    : "That file type does not match this import action."
 869                DomainDebugLog.error("DataPortabilitySettingsView.handleImportResult kindMismatch message=\(message)")
 870                recordImportDebugStatus("Kind mismatch: \(message)")
 871                presentImportError(message)
 872                return
 873            }
 874
 875            DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult presentingPreview kind=\(preview.kind.rawValue)")
 876            recordImportDebugStatus("Presenting preview for \(preview.kind.rawValue)")
 877            presentImportPreview(preview)
 878        } catch {
 879            DomainDebugLog.error("DataPortabilitySettingsView.handleImportResult failed error=\(error.localizedDescription)")
 880            recordImportDebugStatus("Import failed: \(error.localizedDescription)")
 881            presentImportError(error.localizedDescription)
 882        }
 883    }
 884
 885    private func applyPendingImport() {
 886        guard let pendingImportPreview else { return }
 887        do {
 888            _ = try viewModel.applyDataImport(pendingImportPreview, mode: importMode)
 889            self.pendingImportPreview = nil
 890        } catch {
 891            pendingImportError = error.localizedDescription
 892        }
 893    }
 894
 895    private func portabilityFilename(suffix: String, fileExtension: String) -> String {
 896        let formatter = DateFormatter()
 897        formatter.dateFormat = "yyyyMMdd_HHmmss"
 898        return "\(formatter.string(from: Date()))_domaindig_\(suffix).\(fileExtension)"
 899    }
 900
 901    private func presentImportPreview(_ preview: DataImportPreview) {
 902        Task { @MainActor in
 903            try? await Task.sleep(for: .milliseconds(300))
 904            DomainDebugLog.debug("DataPortabilitySettingsView.presentImportPreview kind=\(preview.kind.rawValue) fileName=\(preview.fileName)")
 905            recordImportDebugStatus("Preview presented for \(preview.fileName)")
 906            pendingImportPreview = preview
 907        }
 908    }
 909
 910    private func presentImportError(_ message: String) {
 911        Task { @MainActor in
 912            try? await Task.sleep(for: .milliseconds(300))
 913            DomainDebugLog.error("DataPortabilitySettingsView.presentImportError message=\(message)")
 914            recordImportDebugStatus("Error presented: \(message)")
 915            pendingImportError = message
 916        }
 917    }
 918
 919    private func recordImportDebugStatus(_ message: String) {
 920        #if DEBUG
 921        let status = "[Import Debug] \(message)"
 922        importDebugStatus = status
 923        print(status)
 924        #endif
 925    }
 926}
 927
 928private struct DataManagementSettingsView: View {
 929    @Bindable var viewModel: DomainViewModel
 930    @Environment(\.accessibilityReduceTransparency) private var reduceTransparency
 931
 932    @State private var showClearHistoryConfirmation = false
 933    @State private var showClearCacheConfirmation = false
 934    @State private var showClearWorkflowsConfirmation = false
 935    @State private var showClearTrackedDomainsConfirmation = false
 936    @State private var showDeleteAllConfirmation = false
 937    @State private var deleteAllErrorMessage: String?
 938    @State private var deleteAllSuccessMessage: String?
 939    @State private var isDeletingAllData = false
 940
 941    var body: some View {
 942        Form {
 943            Section("Data") {
 944                Button("Clear History", role: .destructive) {
 945                    showClearHistoryConfirmation = true
 946                }
 947
 948                Button("Clear Cache", role: .destructive) {
 949                    showClearCacheConfirmation = true
 950                }
 951
 952                Button("Clear Workflows", role: .destructive) {
 953                    showClearWorkflowsConfirmation = true
 954                }
 955
 956                Button("Clear Tracked Domains", role: .destructive) {
 957                    showClearTrackedDomainsConfirmation = true
 958                }
 959            }
 960
 961            Section {
 962                Button(role: .destructive) {
 963                    showDeleteAllConfirmation = true
 964                } label: {
 965                    HStack {
 966                        Text("Delete All Data")
 967                        Spacer()
 968                        if isDeletingAllData {
 969                            ProgressView()
 970                                .controlSize(.small)
 971                        }
 972                    }
 973                }
 974                .disabled(isDeletingAllData)
 975            } header: {
 976                Text("Danger Zone")
 977            } footer: {
 978                Text("Permanently removes all local DomainDig data from this device.")
 979            }
 980        }
 981        .disabled(isDeletingAllData)
 982        .navigationTitle("Data Management")
 983        .alert("Clear history?", isPresented: $showClearHistoryConfirmation) {
 984            Button("Clear", role: .destructive) {
 985                viewModel.clearHistory()
 986            }
 987            Button("Cancel", role: .cancel) { /* Dismiss only; SwiftUI closes the alert. */ }
 988        } message: {
 989            Text("This removes saved lookup snapshots and clears monitoring run history on this device.")
 990        }
 991        .alert("Clear cache?", isPresented: $showClearCacheConfirmation) {
 992            Button("Clear", role: .destructive) {
 993                viewModel.clearLookupCache()
 994            }
 995            Button("Cancel", role: .cancel) { /* Dismiss only; SwiftUI closes the alert. */ }
 996        } message: {
 997            Text("This clears the in-memory lookup cache and cancels any cached in-flight work.")
 998        }
 999        .alert("Clear workflows?", isPresented: $showClearWorkflowsConfirmation) {
1000            Button("Clear", role: .destructive) {
1001                viewModel.clearWorkflows()
1002            }
1003            Button("Cancel", role: .cancel) { /* Dismiss only; SwiftUI closes the alert. */ }
1004        } message: {
1005            Text("This removes saved workflows only. History, tracked domains, and saved reports stay intact.")
1006        }
1007        .alert("Clear tracked domains?", isPresented: $showClearTrackedDomainsConfirmation) {
1008            Button("Clear", role: .destructive) {
1009                viewModel.clearTrackedDomains()
1010            }
1011            Button("Cancel", role: .cancel) { /* Dismiss only; SwiftUI closes the alert. */ }
1012        } message: {
1013            Text("This removes the watchlist and clears monitoring run history. History and workflows stay intact.")
1014        }
1015        .alert("Delete All Data?", isPresented: $showDeleteAllConfirmation) {
1016            Button("Cancel", role: .cancel) { /* Dismiss only; SwiftUI closes the alert. */ }
1017            Button("Delete All Data", role: .destructive) {
1018                deleteAllData()
1019            }
1020        } message: {
1021            Text("This will permanently remove all saved DomainDig data from this device. This includes tracked domains, monitoring history, snapshots, exports, cached reports, and local settings. This action cannot be undone.")
1022        }
1023        .alert("Delete Failed", isPresented: Binding(
1024            get: { deleteAllErrorMessage != nil },
1025            set: { if !$0 { deleteAllErrorMessage = nil } }
1026        )) {
1027            Button("OK", role: .cancel) { /* Dismiss only; SwiftUI closes the alert. */ }
1028        } message: {
1029            Text(deleteAllErrorMessage ?? "The local data reset could not be completed.")
1030        }
1031        .safeAreaInset(edge: .bottom) {
1032            if let deleteAllSuccessMessage {
1033                Text(deleteAllSuccessMessage)
1034                    .font(.footnote.weight(.medium))
1035                    .foregroundStyle(Color(.appTextSecondary))
1036                    .padding(.horizontal, 14)
1037                    .padding(.vertical, 10)
1038                    // Reduce Transparency swaps the blur for an opaque surface.
1039                    // On iOS 26+ the system also composites its own translucency
1040                    // that the app cannot declare — verify there too (Phase 6).
1041                    .background(
1042                        Capsule().fill(reduceTransparency ? AnyShapeStyle(Color(.appSurfaceElevated)) : AnyShapeStyle(.thinMaterial))
1043                    )
1044                    .padding(.bottom, 8)
1045                    .transition(.move(edge: .bottom).combined(with: .opacity))
1046            }
1047        }
1048    }
1049
1050    private func deleteAllData() {
1051        guard !isDeletingAllData else { return }
1052
1053        isDeletingAllData = true
1054        deleteAllErrorMessage = nil
1055        deleteAllSuccessMessage = nil
1056
1057        Task {
1058            do {
1059                try await DataResetService.wipeAllLocalData(viewModel: viewModel)
1060                deleteAllSuccessMessage = "All local data removed."
1061                try? await Task.sleep(for: .seconds(2))
1062                if deleteAllSuccessMessage == "All local data removed." {
1063                    deleteAllSuccessMessage = nil
1064                }
1065            } catch {
1066                deleteAllErrorMessage = error.localizedDescription
1067            }
1068
1069            isDeletingAllData = false
1070        }
1071    }
1072}
1073
1074private struct DataImportPreviewSheet: View {
1075    @Environment(\.dismiss) private var dismiss
1076
1077    let preview: DataImportPreview
1078    let mode: DataPortabilityImportMode
1079    let onCancel: () -> Void
1080    let onApply: () -> Void
1081
1082    var body: some View {
1083        NavigationStack {
1084            List {
1085                Section("Summary") {
1086                    ForEach(preview.summaryLines, id: \.self) { line in
1087                        Text(line)
1088                    }
1089                }
1090
1091                Section("Projected Counts") {
1092                    LabeledContent("Tracked Domains", value: "\(preview.projectedCounts.trackedDomains)")
1093                    LabeledContent("History Snapshots", value: "\(preview.projectedCounts.historySnapshots)")
1094                    LabeledContent("Audit Sessions", value: "\(preview.projectedCounts.auditSessions)")
1095                    LabeledContent("Workflows", value: "\(preview.projectedCounts.workflows)")
1096                    LabeledContent("Cached Items", value: "\(preview.projectedCounts.cachedItems)")
1097                    LabeledContent("Monitoring Logs", value: "\(preview.projectedCounts.monitoringLogs)")
1098                }
1099
1100                if !preview.warnings.isEmpty {
1101                    Section("Warnings") {
1102                        ForEach(preview.warnings, id: \.self) { warning in
1103                            Text(warning)
1104                                .foregroundStyle(Color(.appTextSecondary))
1105                        }
1106                    }
1107                }
1108            }
1109            .navigationTitle("Import Preview")
1110            .toolbar {
1111                ToolbarItem(placement: .cancellationAction) {
1112                    Button("Cancel") {
1113                        onCancel()
1114                        dismiss()
1115                    }
1116                }
1117                ToolbarItem(placement: .confirmationAction) {
1118                    Button(mode == .replace ? "Replace" : "Import") {
1119                        onApply()
1120                        if mode == .merge {
1121                            dismiss()
1122                        }
1123                    }
1124                }
1125            }
1126        }
1127    }
1128}