DomainDig/ResultSectionViews.swift

1119 lines · 50243 bytes

   1import MapKit
   2import SwiftUI
   3
   4// Result detail section views extracted from ContentView.swift — one per
   5// inspection domain (availability/DNS, ownership, intelligence, subdomains,
   6// DNS records, web, email, network, ports). Pure presentation over the
   7// view-model report data; the shared primitives (CardView, SectionTitleView,
   8// LabeledValueRow, ResultColors, appLoadingStyle) remain in ContentView.swift.
   9
  10struct DomainSectionView: View {
  11    @Environment(\.appDensity) private var appDensity
  12    @Binding var isCollapsed: Bool
  13    let rows: [InfoRowViewData]
  14    let suggestions: [DomainSuggestionViewData]
  15    let showSuggestions: Bool
  16    let availabilityLoading: Bool
  17    let suggestionsLoading: Bool
  18    let provenance: SectionProvenance?
  19    let confidence: ConfidenceLevel?
  20    let snapshotNote: String?
  21    let trackedDomain: TrackedDomain?
  22    let workflows: [DomainWorkflow]
  23    let trackingLimitMessage: String?
  24    let onTrack: () -> Void
  25    let onTogglePinned: () -> Void
  26    let onEditNote: (() -> Void)?
  27    let onAddToWorkflow: (() -> Void)?
  28    let onOpenWorkflow: ((DomainWorkflow) -> Void)?
  29    let onRunWorkflow: ((DomainWorkflow) -> Void)?
  30
  31    var body: some View {
  32        CollapsibleSectionView(title: "Domain", isCollapsed: $isCollapsed) {
  33            if let trackedDomain {
  34                HStack(spacing: 8) {
  35                    // Icon-only: the header also carries Pin and Note, and the
  36                    // full "Tracked" pill compresses at larger text sizes.
  37                    // VoiceOver still hears the word via the label.
  38                    Image(systemName: "eye.fill")
  39                        .font(appDensity.font(.caption))
  40                        .foregroundStyle(Color(.statusPositive))
  41                        .padding(6)
  42                        .background(Color(.statusPositiveSurface), in: Circle())
  43                        .fixedSize()
  44                        .accessibilityLabel("Tracked")
  45                    Button {
  46                        onTogglePinned()
  47                    } label: {
  48                        Image(systemName: trackedDomain.isPinned ? "pin.fill" : "pin")
  49                    }
  50                    .buttonStyle(.bordered)
  51                    .font(appDensity.font(.caption))
  52                    .accessibilityLabel("Pin domain")
  53                    .accessibilityValue(trackedDomain.isPinned ? "Pinned" : "Not pinned")
  54                    .accessibilityAddTraits(trackedDomain.isPinned ? .isSelected : [])
  55                    if let onEditNote {
  56                        Button("Note") {
  57                            onEditNote()
  58                        }
  59                        .buttonStyle(.bordered)
  60                        .font(appDensity.font(.caption))
  61                        // Never compress into a vertical letter column.
  62                        .fixedSize()
  63                    }
  64                }
  65            } else {
  66                Button("Track") {
  67                    AppHaptics.track()
  68                    onTrack()
  69                }
  70                .buttonStyle(.bordered)
  71                .font(appDensity.font(.caption))
  72                .fixedSize()
  73            }
  74        } content: {
  75            CardView(allowsHorizontalScroll: false) {
  76                SectionTrustMetadataView(
  77                    provenance: provenance,
  78                    confidence: confidence,
  79                    note: snapshotNote == nil ? nil : "Audit note present"
  80                )
  81                ForEach(rows) { row in
  82                    LabeledValueRow(row: row)
  83                }
  84                if let trackedDomain {
  85                    TrackedDomainDetailHeaderView(trackedDomain: trackedDomain)
  86                        .padding(.top, 4)
  87                } else if let trackingLimitMessage {
  88                    MessageRowView(text: trackingLimitMessage, isError: false)
  89                        .padding(.top, 4)
  90                }
  91                if let onAddToWorkflow {
  92                    Button {
  93                        onAddToWorkflow()
  94                    } label: {
  95                        Label("Add to workflow", systemImage: "plus.rectangle.on.folder")
  96                            .font(appDensity.font(.caption))
  97                    }
  98                    .buttonStyle(.bordered)
  99                    .padding(.top, 4)
 100                }
 101                if !workflows.isEmpty {
 102                    VStack(alignment: .leading, spacing: 8) {
 103                        Text("Part of workflow")
 104                            .font(appDensity.font(.caption))
 105                            .foregroundStyle(Color(.appTextSecondary))
 106
 107                        ForEach(workflows) { workflow in
 108                            HStack {
 109                                Text(workflow.name)
 110                                    .font(appDensity.font(.caption))
 111                                    .foregroundStyle(.primary)
 112                                Spacer()
 113                                if let onOpenWorkflow {
 114                                    Button("Open") {
 115                                        onOpenWorkflow(workflow)
 116                                    }
 117                                    .buttonStyle(.bordered)
 118                                    .font(appDensity.font(.caption2))
 119                                }
 120                                if let onRunWorkflow {
 121                                    Button("Run") {
 122                                        onRunWorkflow(workflow)
 123                                    }
 124                                    .buttonStyle(.bordered)
 125                                    .font(appDensity.font(.caption2))
 126                                }
 127                            }
 128                        }
 129                    }
 130                    .padding(.top, 4)
 131                }
 132                if availabilityLoading {
 133                    ProgressView("Checking availability…")
 134                        .appLoadingStyle()
 135                        .padding(.top, 4)
 136                }
 137                if showSuggestions {
 138                    Text("Suggestions")
 139                        .font(appDensity.font(.caption))
 140                        .foregroundStyle(Color(.appTextSecondary))
 141                        .padding(.top, 4)
 142                    if suggestionsLoading {
 143                        ProgressView("Checking alternatives…")
 144                            .appLoadingStyle()
 145                    } else if suggestions.isEmpty {
 146                        MessageRowView(text: "No suggestions", isError: false)
 147                    } else {
 148                        ForEach(suggestions) { suggestion in
 149                            HStack {
 150                                Text(suggestion.domain)
 151                                    .font(appDensity.font(.caption))
 152                                    .foregroundStyle(.primary)
 153                                    .textSelection(.enabled)
 154                                Spacer()
 155                                AppStatusBadgeView(model: AppStatusFactory.availability(suggestion.availabilityStatus))
 156                            }
 157                        }
 158                    }
 159                }
 160            }
 161        }
 162    }
 163}
 164
 165struct OwnershipSectionView: View {
 166    @Environment(\.appDensity) private var appDensity
 167    @Binding var isCollapsed: Bool
 168    let rows: [InfoRowViewData]
 169    let loading: Bool
 170    let error: String?
 171    let provenance: SectionProvenance?
 172    let confidence: ConfidenceLevel?
 173    let history: [DomainOwnershipHistoryEvent]
 174    let historyLoading: Bool
 175    let historyError: String?
 176    let onLoadHistory: (() -> Void)?
 177
 178    init(
 179        isCollapsed: Binding<Bool>,
 180        rows: [InfoRowViewData],
 181        loading: Bool,
 182        error: String?,
 183        provenance: SectionProvenance?,
 184        confidence: ConfidenceLevel?,
 185        history: [DomainOwnershipHistoryEvent] = [],
 186        historyLoading: Bool = false,
 187        historyError: String? = nil,
 188        onLoadHistory: (() -> Void)? = nil
 189    ) {
 190        _isCollapsed = isCollapsed
 191        self.rows = rows
 192        self.loading = loading
 193        self.error = error
 194        self.provenance = provenance
 195        self.confidence = confidence
 196        self.history = history
 197        self.historyLoading = historyLoading
 198        self.historyError = historyError
 199        self.onLoadHistory = onLoadHistory
 200    }
 201
 202    var body: some View {
 203        CollapsibleSectionView(title: "Ownership", isCollapsed: $isCollapsed) {
 204            CardView(allowsHorizontalScroll: false) {
 205                SectionTrustMetadataView(provenance: provenance, confidence: confidence)
 206                if loading {
 207                    ProgressView("Fetching RDAP ownership…")
 208                        .appLoadingStyle()
 209                } else {
 210                    ForEach(rows) { row in
 211                        LabeledValueRow(row: row)
 212                    }
 213                    if let error, rows.allSatisfy({ $0.value == "Unavailable" }) {
 214                        MessageRowView(text: error, isError: error != "Unavailable")
 215                            .padding(.top, 4)
 216                    }
 217                    historyBlock
 218                }
 219            }
 220        }
 221    }
 222
 223    @ViewBuilder
 224    private var historyBlock: some View {
 225        VStack(alignment: .leading, spacing: 8) {
 226            HStack {
 227                Text("History")
 228                    .font(appDensity.font(.caption))
 229                    .foregroundStyle(Color(.appTextSecondary))
 230                Spacer()
 231                if let onLoadHistory, history.isEmpty, !historyLoading {
 232                    Button("Load") {
 233                        onLoadHistory()
 234                    }
 235                    .buttonStyle(.bordered)
 236                    .font(appDensity.font(.caption2))
 237                }
 238            }
 239            if historyLoading {
 240                ProgressView("Loading history…")
 241                    .appLoadingStyle()
 242            } else if !history.isEmpty {
 243                ForEach(history) { event in
 244                    VStack(alignment: .leading, spacing: 3) {
 245                        Text(event.date.formatted(date: .abbreviated, time: .omitted))
 246                            .font(appDensity.font(.caption2))
 247                            .foregroundStyle(Color(.appTextSecondary))
 248                        Text(event.summary)
 249                            .font(appDensity.font(.caption))
 250                        Text(event.source)
 251                            .font(appDensity.font(.caption2))
 252                            .foregroundStyle(Color(.appTextSecondary))
 253                    }
 254                }
 255            } else if let historyError {
 256                MessageRowView(text: historyError, isError: false)
 257            }
 258        }
 259    }
 260}
 261
 262struct IntelligenceSectionView: View {
 263    @Environment(\.appDensity) private var appDensity
 264    @Binding var isCollapsed: Bool
 265    let report: DomainReport
 266    let showsPlaceholder: Bool
 267
 268    var body: some View {
 269        CollapsibleSectionView(title: "Data+ Intelligence", isCollapsed: $isCollapsed) {
 270            CardView(allowsHorizontalScroll: false) {
 271                if showsPlaceholder {
 272                    MessageRowView(text: "Richer intelligence history, hosting analysis, and risk signals are available in Pro+", isError: false)
 273                } else {
 274                    if let provider = report.inferredProvider {
 275                        intelligenceBlock(title: "Infrastructure") {
 276                            LabeledValueRow(row: .init(label: "Provider", value: provider.name, tone: .primary))
 277                            if !provider.evidence.isEmpty {
 278                                MessageRowView(text: provider.evidence.joined(separator: " • "), isError: false)
 279                            }
 280                            if !report.priorProviders.isEmpty {
 281                                LabeledValueRow(row: .init(label: "Prior", value: report.priorProviders.joined(separator: ", "), tone: .secondary))
 282                            }
 283                        }
 284                    }
 285                    if let classification = report.domainClassification {
 286                        intelligenceBlock(title: "Classification") {
 287                            LabeledValueRow(row: .init(label: "Purpose", value: classification.kind.title, tone: .primary))
 288                            MessageRowView(text: classification.reasons.joined(separator: " • "), isError: false)
 289                        }
 290                    }
 291                    intelligenceBlock(title: "Risk Signals") {
 292                        if report.riskSignals.isEmpty {
 293                            MessageRowView(text: "No material historical risk signals detected", isError: false)
 294                        } else {
 295                            ForEach(report.riskSignals.prefix(4)) { signal in
 296                                VStack(alignment: .leading, spacing: 3) {
 297                                    Text(signal.title)
 298                                        .font(appDensity.font(.caption, weight: .semibold))
 299                                    Text(signal.detail)
 300                                        .font(appDensity.font(.caption2))
 301                                        .foregroundStyle(Color(.appTextSecondary))
 302                                }
 303                            }
 304                        }
 305                    }
 306                    intelligenceBlock(title: "Ownership History") {
 307                        if report.ownershipTransitions.isEmpty {
 308                            MessageRowView(text: "No ownership transitions observed locally", isError: false)
 309                        } else {
 310                            ForEach(report.ownershipTransitions.prefix(4)) { event in
 311                                intelligenceEventRow(date: event.date, title: event.summary)
 312                            }
 313                        }
 314                    }
 315                    intelligenceBlock(title: "Hosting History") {
 316                        if report.hostingTransitions.isEmpty {
 317                            MessageRowView(text: "No hosting transitions observed locally", isError: false)
 318                        } else {
 319                            ForEach(report.hostingTransitions.prefix(4)) { event in
 320                                intelligenceEventRow(date: event.date, title: event.summary)
 321                            }
 322                        }
 323                    }
 324                    intelligenceBlock(title: "Subdomain Intelligence") {
 325                        if report.subdomainHistory.isEmpty {
 326                            MessageRowView(text: "No subdomain history available", isError: false)
 327                        } else {
 328                            ForEach(report.subdomainHistory.prefix(5)) { item in
 329                                VStack(alignment: .leading, spacing: 3) {
 330                                    HStack {
 331                                        Text(item.hostname)
 332                                            .font(appDensity.font(.caption))
 333                                        Spacer()
 334                                        if item.isEphemeral {
 335                                            Text("Ephemeral")
 336                                                .font(appDensity.font(.caption2))
 337                                                .foregroundStyle(Color(.statusWarning))
 338                                        }
 339                                    }
 340                                    Text("First \(item.firstSeen.formatted(date: .abbreviated, time: .omitted)) • Last \(item.lastSeen.formatted(date: .abbreviated, time: .omitted)) • Seen \(item.recurrenceCount)x")
 341                                        .font(appDensity.font(.caption2))
 342                                        .foregroundStyle(Color(.appTextSecondary))
 343                                }
 344                            }
 345                        }
 346                    }
 347                    intelligenceBlock(title: "Timeline") {
 348                        if report.intelligenceTimeline.isEmpty {
 349                            MessageRowView(text: "No inferred intelligence events yet", isError: false)
 350                        } else {
 351                            ForEach(report.intelligenceTimeline.prefix(5)) { event in
 352                                intelligenceEventRow(date: event.date, title: "\(event.title): \(event.detail)")
 353                            }
 354                        }
 355                    }
 356                }
 357            }
 358        }
 359    }
 360
 361    @ViewBuilder
 362    private func intelligenceBlock<Content: View>(title: String, @ViewBuilder content: () -> Content) -> some View {
 363        VStack(alignment: .leading, spacing: 8) {
 364            Text(title)
 365                .font(appDensity.font(.subheadline, weight: .semibold))
 366                .foregroundStyle(Color(.statusInfo))
 367            content()
 368        }
 369    }
 370
 371    private func intelligenceEventRow(date: Date, title: String) -> some View {
 372        VStack(alignment: .leading, spacing: 3) {
 373            Text(date.formatted(date: .abbreviated, time: .omitted))
 374                .font(appDensity.font(.caption2))
 375                .foregroundStyle(Color(.appTextSecondary))
 376            Text(title)
 377                .font(appDensity.font(.caption))
 378        }
 379    }
 380}
 381
 382struct SubdomainsSectionView: View {
 383    @Environment(\.appDensity) private var appDensity
 384    @Binding var isCollapsed: Bool
 385    let rows: [SubdomainRowViewData]
 386    let groups: [SubdomainGroup]
 387    let loading: Bool
 388    let error: String?
 389    let provenance: SectionProvenance?
 390    let confidence: ConfidenceLevel?
 391    let showsExtendedPlaceholder: Bool
 392    let extendedCount: Int
 393    let extendedLoading: Bool
 394    let extendedError: String?
 395    let onLoadExtended: (() -> Void)?
 396
 397    init(
 398        isCollapsed: Binding<Bool>,
 399        rows: [SubdomainRowViewData],
 400        groups: [SubdomainGroup],
 401        loading: Bool,
 402        error: String?,
 403        provenance: SectionProvenance?,
 404        confidence: ConfidenceLevel?,
 405        showsExtendedPlaceholder: Bool,
 406        extendedCount: Int = 0,
 407        extendedLoading: Bool = false,
 408        extendedError: String? = nil,
 409        onLoadExtended: (() -> Void)? = nil
 410    ) {
 411        _isCollapsed = isCollapsed
 412        self.rows = rows
 413        self.groups = groups
 414        self.loading = loading
 415        self.error = error
 416        self.provenance = provenance
 417        self.confidence = confidence
 418        self.showsExtendedPlaceholder = showsExtendedPlaceholder
 419        self.extendedCount = extendedCount
 420        self.extendedLoading = extendedLoading
 421        self.extendedError = extendedError
 422        self.onLoadExtended = onLoadExtended
 423    }
 424
 425    var body: some View {
 426        CollapsibleSectionView(title: "Subdomains", isCollapsed: $isCollapsed, subtitle: "\(rows.count) found") {
 427            CardView(allowsHorizontalScroll: false) {
 428                SectionTrustMetadataView(provenance: provenance, confidence: confidence)
 429                if loading {
 430                    ProgressView("Checking certificate transparency…")
 431                        .appLoadingStyle()
 432                } else if rows.isEmpty {
 433                    MessageRowView(text: error ?? "No passive subdomains found", isError: false)
 434                    if showsExtendedPlaceholder {
 435                        MessageRowView(text: "Extended subdomain discovery available in Pro+", isError: false)
 436                            .padding(.top, 4)
 437                    }
 438                } else {
 439                    if let onLoadExtended, extendedCount == 0, !extendedLoading, !showsExtendedPlaceholder {
 440                        Button("Load extended results") {
 441                            onLoadExtended()
 442                        }
 443                        .buttonStyle(.bordered)
 444                        .font(appDensity.font(.caption2))
 445                    }
 446                    groupList
 447                    subdomainRows
 448                    extendedStatus
 449                }
 450            }
 451        }
 452    }
 453
 454    @ViewBuilder
 455    private var extendedStatus: some View {
 456        if extendedLoading {
 457            ProgressView("Loading extended subdomains…")
 458                .appLoadingStyle()
 459                .padding(.top, 4)
 460        } else if extendedCount > 0 {
 461            MessageRowView(text: "\(extendedCount) extended results included", isError: false)
 462                .padding(.top, 4)
 463        } else if let extendedError {
 464            MessageRowView(text: extendedError, isError: false)
 465                .padding(.top, 4)
 466        } else if showsExtendedPlaceholder {
 467            MessageRowView(text: "Extended subdomain discovery available in Pro+", isError: false)
 468                .padding(.top, 4)
 469        }
 470    }
 471
 472    @ViewBuilder
 473    private var groupList: some View {
 474        if !groups.isEmpty {
 475            Text("Groups")
 476                .font(appDensity.font(.caption2))
 477                .foregroundStyle(Color(.appTextSecondary))
 478            ForEach(groups) { group in
 479                HStack {
 480                    Text("\(group.label).*")
 481                        .font(appDensity.font(.caption))
 482                        .foregroundStyle(Color(.statusInfo))
 483                    Spacer()
 484                    Text("\(group.subdomains.count)")
 485                        .font(appDensity.font(.caption2))
 486                        .foregroundStyle(Color(.appTextSecondary))
 487                }
 488            }
 489        }
 490    }
 491
 492    @ViewBuilder
 493    private var subdomainRows: some View {
 494        ForEach(rows) { row in
 495            HStack(spacing: 8) {
 496                Text(row.hostname)
 497                    .font(appDensity.font(.caption))
 498                    .foregroundStyle(.primary)
 499                    .textSelection(.enabled)
 500                Spacer()
 501                if row.isInteresting {
 502                    Text("Interesting")
 503                        .font(.system(.caption2, design: .monospaced))
 504                        .foregroundStyle(Color(.statusWarning))
 505                        .padding(.horizontal, 8)
 506                        .padding(.vertical, 4)
 507                        .background(Color(.statusWarningSurface))
 508                        .clipShape(Capsule())
 509                }
 510            }
 511        }
 512    }
 513}
 514
 515struct DNSSectionView: View {
 516    @Environment(\.appDensity) private var appDensity
 517    @Binding var isCollapsed: Bool
 518    let dnssecLabel: String?
 519    let patternSummary: DNSPatternSummary?
 520    let sections: [DNSRecordSectionViewData]
 521    let ptrMessage: SectionMessageViewData?
 522    let loading: Bool
 523    let dnsProvenance: SectionProvenance?
 524    let ptrProvenance: SectionProvenance?
 525    let sectionError: String?
 526    let history: [DNSHistoryEvent]
 527    let historyLoading: Bool
 528    let historyError: String?
 529    let onLoadHistory: (() -> Void)?
 530
 531    init(
 532        isCollapsed: Binding<Bool>,
 533        dnssecLabel: String?,
 534        patternSummary: DNSPatternSummary?,
 535        sections: [DNSRecordSectionViewData],
 536        ptrMessage: SectionMessageViewData?,
 537        loading: Bool,
 538        dnsProvenance: SectionProvenance?,
 539        ptrProvenance: SectionProvenance?,
 540        sectionError: String?,
 541        history: [DNSHistoryEvent] = [],
 542        historyLoading: Bool = false,
 543        historyError: String? = nil,
 544        onLoadHistory: (() -> Void)? = nil
 545    ) {
 546        _isCollapsed = isCollapsed
 547        self.dnssecLabel = dnssecLabel
 548        self.patternSummary = patternSummary
 549        self.sections = sections
 550        self.ptrMessage = ptrMessage
 551        self.loading = loading
 552        self.dnsProvenance = dnsProvenance
 553        self.ptrProvenance = ptrProvenance
 554        self.sectionError = sectionError
 555        self.history = history
 556        self.historyLoading = historyLoading
 557        self.historyError = historyError
 558        self.onLoadHistory = onLoadHistory
 559    }
 560
 561    var body: some View {
 562        CollapsibleSectionView(title: "DNS", isCollapsed: $isCollapsed, subtitle: dnssecLabel) {
 563            if loading {
 564                LoadingCardView(text: "Querying DNS…")
 565            } else if let sectionError, sections.isEmpty {
 566                MessageCardView(text: sectionError, isError: true)
 567            } else {
 568                provenanceCard
 569                ForEach(sections) { section in
 570                    CardView {
 571                        Text(section.title)
 572                            .font(.system(.subheadline, design: .monospaced))
 573                            .fontWeight(.semibold)
 574                            .foregroundStyle(Color(.statusInfo))
 575
 576                        if let message = section.message {
 577                            MessageRowView(text: message.text, isError: message.isError)
 578                        }
 579
 580                        ForEach(section.rows) { row in
 581                            LabeledValueRow(row: row)
 582                        }
 583
 584                        if let wildcardTitle = section.wildcardTitle {
 585                            Text(wildcardTitle)
 586                                .font(.system(.caption, design: .monospaced))
 587                                .foregroundStyle(Color(.appTextSecondary))
 588                                .padding(.top, 4)
 589                            ForEach(section.wildcardRows) { row in
 590                                LabeledValueRow(row: row)
 591                            }
 592                        }
 593                    }
 594                }
 595
 596                if let ptrMessage {
 597                    CardView {
 598                        Text("PTR")
 599                            .font(.system(.subheadline, design: .monospaced))
 600                            .fontWeight(.semibold)
 601                            .foregroundStyle(Color(.statusInfo))
 602                        SectionTrustMetadataView(provenance: ptrProvenance, confidence: nil)
 603                        MessageRowView(text: ptrMessage.text, isError: ptrMessage.isError)
 604                    }
 605                }
 606
 607                CardView(allowsHorizontalScroll: false) {
 608                    HStack {
 609                        Text("History")
 610                            .font(appDensity.font(.subheadline, weight: .semibold))
 611                            .foregroundStyle(Color(.statusInfo))
 612                        Spacer()
 613                        if let onLoadHistory, history.isEmpty, !historyLoading {
 614                            Button("Load") {
 615                                onLoadHistory()
 616                            }
 617                            .buttonStyle(.bordered)
 618                            .font(appDensity.font(.caption2))
 619                        }
 620                    }
 621                    historyContent
 622                }
 623            }
 624        }
 625    }
 626
 627    @ViewBuilder
 628    private var historyContent: some View {
 629        if historyLoading {
 630            ProgressView("Loading DNS history…")
 631                .appLoadingStyle()
 632        } else if !history.isEmpty {
 633            ForEach(history) { event in
 634                VStack(alignment: .leading, spacing: 3) {
 635                    Text(event.date.formatted(date: .abbreviated, time: .omitted))
 636                        .font(appDensity.font(.caption2))
 637                        .foregroundStyle(Color(.appTextSecondary))
 638                    Text(event.summary)
 639                        .font(appDensity.font(.caption))
 640                    if !event.aRecords.isEmpty {
 641                        Text("A: \(event.aRecords.joined(separator: ", "))")
 642                            .font(appDensity.font(.caption2))
 643                            .foregroundStyle(Color(.appTextSecondary))
 644                    }
 645                    if !event.nameservers.isEmpty {
 646                        Text("NS: \(event.nameservers.joined(separator: ", "))")
 647                            .font(appDensity.font(.caption2))
 648                            .foregroundStyle(Color(.appTextSecondary))
 649                    }
 650                }
 651            }
 652        } else if let historyError {
 653            MessageRowView(text: historyError, isError: false)
 654        }
 655    }
 656
 657    @ViewBuilder
 658    private var provenanceCard: some View {
 659        if dnsProvenance != nil {
 660            CardView(allowsHorizontalScroll: false) {
 661                SectionTrustMetadataView(provenance: dnsProvenance, confidence: nil)
 662                if let patternSummary {
 663                    if !patternSummary.providers.isEmpty {
 664                        MessageRowView(text: "Providers: \(patternSummary.providers.joined(separator: ", "))", isError: false)
 665                    }
 666                    if !patternSummary.patterns.isEmpty {
 667                        ForEach(Array(patternSummary.patterns.enumerated()), id: \.offset) { _, pattern in
 668                            MessageRowView(text: pattern, isError: false)
 669                        }
 670                    }
 671                }
 672            }
 673        }
 674    }
 675}
 676
 677struct WebSectionView: View {
 678    @Environment(\.appDensity) private var appDensity
 679    @Binding var isCollapsed: Bool
 680    let certificateRows: [InfoRowViewData]
 681    let sslInfo: SSLCertificateInfo?
 682    let tlsSummary: WebResultSummary?
 683    let sslLoading: Bool
 684    let sslError: String?
 685    let tlsProvenance: SectionProvenance?
 686    let responseRows: [InfoRowViewData]
 687    let headers: [HTTPHeader]
 688    let headersLoading: Bool
 689    let headersError: String?
 690    let httpProvenance: SectionProvenance?
 691    let redirects: [RedirectHopViewData]
 692    let redirectLoading: Bool
 693    let redirectError: String?
 694    let redirectProvenance: SectionProvenance?
 695    let finalURL: String?
 696
 697    var body: some View {
 698        CollapsibleSectionView(title: "Web", isCollapsed: $isCollapsed) {
 699            CardView {
 700                HStack {
 701                    Text("TLS")
 702                        .font(appDensity.font(.subheadline, weight: .semibold))
 703                        .foregroundStyle(Color(.statusInfo))
 704                    Spacer()
 705                    if !sslLoading {
 706                        AppStatusBadgeView(model: AppStatusFactory.tls(sslInfo: sslInfo, error: sslError))
 707                    }
 708                }
 709                SectionTrustMetadataView(provenance: tlsProvenance, confidence: nil)
 710                if !sslLoading, let tlsSummary {
 711                    LabeledValueRow(row: InfoRowViewData(label: "TLS Grade", value: tlsSummary.tlsGrade.rawValue, tone: tlsSummary.tlsGrade.tone))
 712                    ForEach(Array(tlsSummary.tlsHighlights.enumerated()), id: \.offset) { _, highlight in
 713                        MessageRowView(text: highlight, isError: isTLSHighlightError(highlight))
 714                    }
 715                }
 716                if sslLoading {
 717                    ProgressView("Checking certificate…")
 718                        .appLoadingStyle()
 719                } else if let sslError {
 720                    MessageRowView(text: sslError, isError: true)
 721                } else {
 722                    ForEach(certificateRows) { row in
 723                        LabeledValueRow(row: row)
 724                    }
 725                    if let sslInfo, !sslInfo.subjectAltNames.isEmpty {
 726                        Text("SANs")
 727                            .font(appDensity.font(.caption2))
 728                            .foregroundStyle(Color(.appTextSecondary))
 729                        ForEach(sslInfo.subjectAltNames, id: \.self) { san in
 730                            HStack(alignment: .top, spacing: 8) {
 731                                Text(san)
 732                                    .font(appDensity.font(.caption))
 733                                    .lineLimit(nil)
 734                                    .fixedSize(horizontal: false, vertical: true)
 735                                    .textSelection(.enabled)
 736                                Spacer()
 737                                AppCopyButton(value: san, label: "Copy certificate SAN")
 738                            }
 739                        }
 740                    }
 741                }
 742            }
 743
 744            CardView {
 745                Text("Headers")
 746                    .font(appDensity.font(.subheadline, weight: .semibold))
 747                    .foregroundStyle(Color(.statusInfo))
 748                SectionTrustMetadataView(provenance: httpProvenance, confidence: nil)
 749                if headersLoading {
 750                    ProgressView("Fetching headers…")
 751                        .appLoadingStyle()
 752                } else if let headersError {
 753                    MessageRowView(text: headersError, isError: true)
 754                } else {
 755                    ForEach(responseRows) { row in
 756                        LabeledValueRow(row: row)
 757                    }
 758                    if headers.isEmpty {
 759                        MessageRowView(text: "No HTTP headers returned", isError: false)
 760                    } else {
 761                        ForEach(headers) { header in
 762                            HStack(alignment: .top, spacing: 4) {
 763                                Text(header.name + ":")
 764                                    .font(appDensity.font(.caption))
 765                                    .foregroundStyle(header.isSecurityHeader ? Color(.statusWarning) : Color(.statusInfo))
 766                                Text(header.value)
 767                                    .font(appDensity.font(.caption))
 768                                    .foregroundStyle(.primary)
 769                                    .textSelection(.enabled)
 770                            }
 771                        }
 772                    }
 773                }
 774            }
 775
 776            CardView {
 777                HStack {
 778                    Text("Redirects")
 779                        .font(appDensity.font(.subheadline, weight: .semibold))
 780                        .foregroundStyle(Color(.statusInfo))
 781                    Spacer()
 782                    if let finalURL {
 783                        AppCopyButton(value: finalURL, label: "Copy redirect URL")
 784                    }
 785                }
 786                SectionTrustMetadataView(provenance: redirectProvenance, confidence: nil)
 787                if redirectLoading {
 788                    ProgressView("Tracing redirects…")
 789                        .appLoadingStyle()
 790                } else if let redirectError {
 791                    MessageRowView(text: redirectError, isError: true)
 792                } else if redirects.isEmpty {
 793                    MessageRowView(text: "No redirect data available", isError: false)
 794                } else {
 795                    if let finalURL {
 796                        LabeledValueRow(row: InfoRowViewData(label: "Final URL", value: finalURL, tone: .secondary))
 797                    }
 798                    ForEach(redirects) { redirect in
 799                        HStack(alignment: .top, spacing: 6) {
 800                            Text(redirect.stepLabel)
 801                                .font(appDensity.font(.caption))
 802                                .foregroundStyle(Color(.appTextSecondary))
 803                                .frame(width: 16, alignment: .trailing)
 804                            Text(redirect.statusCode)
 805                                .font(appDensity.font(.caption))
 806                                .foregroundStyle(Color(.statusInfo))
 807                                .frame(width: 36, alignment: .leading)
 808                            Text(redirect.url)
 809                                .font(appDensity.font(.caption))
 810                                .textSelection(.enabled)
 811                            if redirect.isFinal {
 812                                Text("(final)")
 813                                    .font(appDensity.font(.caption2))
 814                                    .foregroundStyle(Color(.appTextSecondary))
 815                            }
 816                            Spacer(minLength: 8)
 817                            AppCopyButton(value: redirect.url, label: "Copy redirect URL")
 818                        }
 819                    }
 820                }
 821            }
 822        }
 823    }
 824
 825    private func isTLSHighlightError(_ highlight: String) -> Bool {
 826        let normalized = highlight.lowercased()
 827        if normalized.contains("no weak tls indicators were detected") {
 828            return false
 829        }
 830        return normalized.contains("expires")
 831            || normalized.contains("weak")
 832            || normalized.contains("tls 1.0")
 833            || normalized.contains("tls 1.1")
 834    }
 835}
 836
 837struct EmailSectionView: View {
 838    @Environment(\.appDensity) private var appDensity
 839    @Binding var isCollapsed: Bool
 840    let rows: [EmailRowViewData]
 841    let assessment: EmailSecuritySummary?
 842    let loading: Bool
 843    let provenance: SectionProvenance?
 844    let confidence: ConfidenceLevel?
 845    let error: String?
 846
 847    var body: some View {
 848        CollapsibleSectionView(title: "Email", isCollapsed: $isCollapsed) {
 849            CardView {
 850                SectionTrustMetadataView(provenance: provenance, confidence: confidence)
 851                HStack {
 852                    Spacer()
 853                    AppStatusBadgeView(model: AppStatusFactory.email(nil, error: error))
 854                        .opacity(loading ? 0 : 1)
 855                }
 856                if let assessment, let grade = assessment.grade {
 857                    LabeledValueRow(row: InfoRowViewData(label: "Grade", value: grade.rawValue, tone: grade.tone))
 858                    if !assessment.reasons.isEmpty {
 859                        Text(assessment.reasons.joined(separator: " | "))
 860                            .font(appDensity.font(.caption2))
 861                            .foregroundStyle(Color(.appTextSecondary))
 862                    }
 863                }
 864                if loading {
 865                    ProgressView("Checking email records…")
 866                        .appLoadingStyle()
 867                } else if let error {
 868                    MessageRowView(text: error, isError: true)
 869                } else if rows.isEmpty {
 870                    MessageRowView(text: "No email security records found", isError: false)
 871                } else {
 872                    ForEach(rows) { row in
 873                        VStack(alignment: .leading, spacing: 4) {
 874                            HStack(spacing: 8) {
 875                                Text(row.label)
 876                                    .font(appDensity.font(.caption))
 877                                    .foregroundStyle(Color(.statusInfo))
 878                                    .frame(width: 76, alignment: .leading)
 879                                AppStatusBadgeView(model: emailRowBadge(row))
 880                            }
 881                            Text(row.detail)
 882                                .font(appDensity.font(.caption2))
 883                                .foregroundStyle(.primary)
 884                                .textSelection(.enabled)
 885                            if let auxiliaryDetail = row.auxiliaryDetail {
 886                                Text(auxiliaryDetail)
 887                                    .font(appDensity.font(.caption2))
 888                                    .foregroundStyle(Color(.appTextSecondary))
 889                            }
 890                        }
 891                    }
 892                }
 893            }
 894        }
 895    }
 896
 897    private func emailRowBadge(_ row: EmailRowViewData) -> AppStatusBadgeModel {
 898        switch row.statusTone {
 899        case .success:
 900            return .init(title: row.status, systemImage: "checkmark.shield.fill", foregroundColor: Color(.statusPositive), backgroundColor: Color(.statusPositiveSurface))
 901        case .warning:
 902            return .init(title: row.status, systemImage: "shield.lefthalf.filled", foregroundColor: Color(.statusWarning), backgroundColor: Color(.statusWarningSurface))
 903        case .failure:
 904            return .init(title: row.status, systemImage: "minus.circle", foregroundColor: Color(.appTextSecondary), backgroundColor: Color(.appSurfaceElevated))
 905        case .primary, .secondary:
 906            return .init(title: row.status, systemImage: "circle", foregroundColor: Color(.appTextSecondary), backgroundColor: Color(.appSurfaceElevated))
 907        }
 908    }
 909}
 910
 911struct NetworkSectionView: View {
 912    @Environment(\.appDensity) private var appDensity
 913    @Binding var isCollapsed: Bool
 914    let reachabilityRows: [ReachabilityRowViewData]
 915    let reachabilityLoading: Bool
 916    let reachabilityError: String?
 917    let reachabilityProvenance: SectionProvenance?
 918    let locationRows: [InfoRowViewData]
 919    let geolocation: IPGeolocation?
 920    let geolocationLoading: Bool
 921    let geolocationError: String?
 922    let geolocationProvenance: SectionProvenance?
 923    let geolocationConfidence: ConfidenceLevel?
 924    let standardPortRows: [PortScanRowViewData]
 925    let customPortRows: [PortScanRowViewData]
 926    let portScanLoading: Bool
 927    let portScanError: String?
 928    let portScanProvenance: SectionProvenance?
 929    let customPortScanLoading: Bool
 930    let customPortScanError: String?
 931    let isCloudflareProxied: Bool
 932    @Binding var customPortsExpanded: Bool
 933    @Binding var customPortInput: String
 934    let onScanCustomPorts: () -> Void
 935
 936    var body: some View {
 937        CollapsibleSectionView(title: "Network", isCollapsed: $isCollapsed) {
 938            CardView {
 939                Text("Reachability")
 940                    .font(appDensity.font(.subheadline, weight: .semibold))
 941                    .foregroundStyle(Color(.statusInfo))
 942                SectionTrustMetadataView(provenance: reachabilityProvenance, confidence: nil)
 943                if reachabilityLoading {
 944                    ProgressView("Checking ports…")
 945                        .appLoadingStyle()
 946                } else if let reachabilityError {
 947                    MessageRowView(text: reachabilityError, isError: true)
 948                } else {
 949                    ForEach(reachabilityRows) { row in
 950                        HStack {
 951                            Text(row.portLabel)
 952                                .font(appDensity.font(.caption))
 953                            Spacer()
 954                            Text(row.latencyLabel)
 955                                .font(appDensity.font(.caption2))
 956                                .foregroundStyle(Color(.appTextSecondary))
 957                            AppStatusBadgeView(model: reachabilityBadge(row))
 958                        }
 959                    }
 960                }
 961            }
 962
 963            CardView(allowsHorizontalScroll: false) {
 964                Text("Location")
 965                    .font(appDensity.font(.subheadline, weight: .semibold))
 966                    .foregroundStyle(Color(.statusInfo))
 967                SectionTrustMetadataView(provenance: geolocationProvenance, confidence: geolocationConfidence)
 968                if geolocationLoading {
 969                    ProgressView("Looking up location…")
 970                        .appLoadingStyle()
 971                } else if let geolocationError, geolocation == nil {
 972                    MessageRowView(text: geolocationError, isError: geolocationError != "No A record available")
 973                } else if let geolocation {
 974                    ForEach(locationRows) { row in
 975                        LabeledValueRow(row: row)
 976                    }
 977                    if let latitude = geolocation.latitude, let longitude = geolocation.longitude {
 978                        let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
 979                        Map(initialPosition: .region(MKCoordinateRegion(
 980                            center: coordinate,
 981                            span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1)
 982                        ))) {
 983                            Marker(geolocation.ip, coordinate: coordinate)
 984                        }
 985                        .mapStyle(.standard)
 986                        .frame(maxWidth: .infinity)
 987                        .frame(height: 180)
 988                        .cornerRadius(8)
 989                    }
 990                } else {
 991                    MessageRowView(text: "No location data available", isError: false)
 992                }
 993            }
 994
 995            CardView(allowsHorizontalScroll: false) {
 996                Text("Port Scan")
 997                    .font(appDensity.font(.subheadline, weight: .semibold))
 998                    .foregroundStyle(Color(.statusInfo))
 999                SectionTrustMetadataView(provenance: portScanProvenance, confidence: nil)
1000
1001                if isCloudflareProxied {
1002                    Text("Domain is behind Cloudflare's proxy. Results reflect the edge, not the origin.")
1003                        .font(appDensity.font(.caption2))
1004                        .foregroundStyle(Color(.statusWarning))
1005                        .fixedSize(horizontal: false, vertical: true)
1006                }
1007
1008                if portScanLoading {
1009                    ProgressView("Scanning ports…")
1010                        .appLoadingStyle()
1011                } else if let portScanError, standardPortRows.isEmpty {
1012                    MessageRowView(text: portScanError, isError: true)
1013                } else {
1014                    Text("Standard Ports")
1015                        .font(.system(.caption, design: .monospaced))
1016                        .foregroundStyle(Color(.appTextSecondary))
1017                    PortRowsView(rows: standardPortRows)
1018                }
1019
1020                DisclosureGroup("Custom Ports", isExpanded: $customPortsExpanded) {
1021                    VStack(alignment: .leading, spacing: 10) {
1022                        TextField("8888, 9000, 27017", text: $customPortInput)
1023                            .font(appDensity.font(.caption))
1024                            .textInputAutocapitalization(.never)
1025                            .autocorrectionDisabled()
1026                            .keyboardType(.numberPad)
1027                            .padding(10)
1028                            .background(Color(.appSurface))
1029                            .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
1030
1031                        Button("Scan") {
1032                            AppHaptics.refresh()
1033                            onScanCustomPorts()
1034                        }
1035                        .buttonStyle(.borderedProminent)
1036                        .tint(Color(.accentFill))
1037                        .disabled(customPortScanLoading)
1038
1039                        if customPortScanLoading {
1040                            ProgressView("Scanning custom ports…")
1041                                .appLoadingStyle()
1042                        } else if let customPortScanError {
1043                            MessageRowView(text: customPortScanError, isError: true)
1044                        } else {
1045                            PortRowsView(rows: customPortRows)
1046                        }
1047                    }
1048                    .padding(.top, 8)
1049                }
1050                .font(.system(.caption, design: .monospaced))
1051                .tint(.secondary)
1052            }
1053        }
1054    }
1055
1056    private func reachabilityBadge(_ row: ReachabilityRowViewData) -> AppStatusBadgeModel {
1057        switch row.statusTone {
1058        case .success:
1059            return .init(title: row.statusLabel, systemImage: "checkmark.circle.fill", foregroundColor: Color(.statusPositive), backgroundColor: Color(.statusPositiveSurface))
1060        case .warning:
1061            return .init(title: row.statusLabel, systemImage: "exclamationmark.triangle.fill", foregroundColor: Color(.statusWarning), backgroundColor: Color(.statusWarningSurface))
1062        case .failure:
1063            return .init(title: row.statusLabel, systemImage: "xmark.circle.fill", foregroundColor: Color(.statusCritical), backgroundColor: Color(.statusCriticalSurface))
1064        case .primary, .secondary:
1065            return .init(title: row.statusLabel, systemImage: "circle", foregroundColor: Color(.appTextSecondary), backgroundColor: Color(.appSurfaceElevated))
1066        }
1067    }
1068}
1069
1070struct PortRowsView: View {
1071    @Environment(\.appDensity) private var appDensity
1072    let rows: [PortScanRowViewData]
1073
1074    var body: some View {
1075        if rows.isEmpty {
1076            MessageRowView(text: "No results", isError: false)
1077        } else {
1078            ForEach(rows) { row in
1079                VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing - 1) {
1080                    HStack {
1081                        Text(row.portLabel)
1082                            .font(appDensity.font(.caption))
1083                            .frame(width: 52, alignment: .leading)
1084                        Text(row.service)
1085                            .font(appDensity.font(.caption))
1086                            .foregroundStyle(.primary)
1087                        Spacer()
1088                        if let durationLabel = row.durationLabel {
1089                            Text(durationLabel)
1090                                .font(appDensity.font(.caption2))
1091                                .foregroundStyle(Color(.appTextSecondary))
1092                        }
1093                        AppStatusBadgeView(model: portBadge(row))
1094                    }
1095                    if let banner = row.banner {
1096                        Text(banner)
1097                            .font(appDensity.font(.caption2))
1098                            .foregroundStyle(Color(.appTextSecondary))
1099                            .padding(.leading, 8)
1100                    }
1101                }
1102                .frame(minHeight: appDensity.metrics.rowMinHeight, alignment: .topLeading)
1103            }
1104        }
1105    }
1106
1107    private func portBadge(_ row: PortScanRowViewData) -> AppStatusBadgeModel {
1108        switch row.statusTone {
1109        case .success:
1110            return .init(title: row.statusLabel, systemImage: "checkmark.circle.fill", foregroundColor: Color(.statusPositive), backgroundColor: Color(.statusPositiveSurface))
1111        case .warning:
1112            return .init(title: row.statusLabel, systemImage: "exclamationmark.triangle.fill", foregroundColor: Color(.statusWarning), backgroundColor: Color(.statusWarningSurface))
1113        case .failure:
1114            return .init(title: row.statusLabel, systemImage: "xmark.circle.fill", foregroundColor: Color(.statusCritical), backgroundColor: Color(.statusCriticalSurface))
1115        case .primary, .secondary:
1116            return .init(title: row.statusLabel, systemImage: "circle", foregroundColor: Color(.appTextSecondary), backgroundColor: Color(.appSurfaceElevated))
1117        }
1118    }
1119}