DomainDig/SettingsViews.swift

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