DomainDig/SettingsViews.swift

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