import AgentDeviceSnapshotPresentation
import XCTest

extension RunnerTests {



  static let navigationBarBackButtonIdentifier = "BackButton"



  static let backSwipeVerificationDelay: TimeInterval = 0.1

  static let backSwipeSettleSampleInterval: TimeInterval = 0.05



#if targetEnvironment(simulator)
  static let backGestureAllowanceMs = 200.0
#else
  static let backGestureAllowanceMs = 400.0
#endif


  static let backSwipeSettleBaseBudgetMs = 2000.0





  static let backSwipeStillMarginMs = 250.0





  static func backSwipeSettleBudgetMs(maxCaptureMs: Double) -> Double {
    let sampleIntervalMs = backSwipeSettleSampleInterval * 1000 + maxCaptureMs
    return max(
      backSwipeSettleBaseBudgetMs,
      maxCaptureMs + backSwipeRequiredStillMs(maxCaptureMs: maxCaptureMs) + sampleIntervalMs
    )
  }






  static func backSwipeRequiredStillMs(maxCaptureMs: Double) -> Double {
    backGestureAllowanceMs + backSwipeStillMarginMs + maxCaptureMs
  }



  enum InAppBackOutcome {
    case performed
    case refused(ErrorPayload)
    case unconfirmed(ErrorPayload)
  }


  static let backSwipeDurationMs = 100.0





  static func backSwipeEndpoints(in surface: CGRect) -> (start: CGPoint, end: CGPoint) {
    func axis(_ size: CGFloat, percent: CGFloat) -> CGFloat {
      let margin: CGFloat = 8
      let upper = max(margin, (size - margin).rounded())
      return min(upper, max(margin, (size * percent / 100).rounded(.towardZero)))
    }
    let y = surface.minY + axis(surface.height, percent: 50)
    return (
      CGPoint(x: surface.minX + axis(surface.width, percent: 1), y: y),
      CGPoint(x: surface.minX + axis(surface.width, percent: 85), y: y)
    )
  }




  enum NavigationVisualObservation: Equatable {
    case changed
    case unchanged
    case unobserved(refusal: RunnerAppScreenCaptureFailure)

    var logToken: String {
      switch self {
      case .changed: return "yes"
      case .unchanged: return "no"
      case .unobserved: return "unknown"
      }
    }
  }






  @MainActor
  func performInAppBack(app: XCUIApplication) throws -> InAppBackOutcome {
#if os(macOS)
    guard let back = macOSNavigationBackElement(app: app) else {
      return .refused(Self.macOSInAppBackControlRefusal)
    }
    let frame = back.frame
    if frame.isEmpty {
      back.tap()
    } else {
      _ = try tapAt(app: app, x: frame.midX, y: frame.midY)
    }
    return .performed
#elseif os(tvOS)
    _ = pressTvRemote(.menu)
    return .performed
#elseif os(iOS)


    var trace = BackSwipeTrace()
    func logSwipe(_ line: String) { NSLog("AGENT_DEVICE_RUNNER_BACK_SWIPE_VERIFICATION %@", line) }
    let resolved: SynthesizedCoordinateContext?
    do {
      resolved = try synthesizedCoordinateContext(app: app)
    } catch {
      logSwipe(trace.logLine(name: "error", code: String(describing: type(of: error))))
      throw error
    }
    guard let context = resolved else {
      let outcome = InAppBackOutcome.refused(Self.backScreenRefusal(.unresolvedWindow))
      logSwipe(trace.logLine(outcome: outcome))
      return outcome
    }
    if let pressed = try pressNavigationBarBackButton(app: app, context: context) {
      return pressed
    }
    do {
      var outcome = try verifiedBackSwipe(app: app, context: context, trace: &trace)
      logSwipe(trace.logLine(outcome: outcome))
      if case .unconfirmed(var payload) = outcome, payload.code == RunnerWireErrorCode.backSwipeNoChange {
        payload.dismissControls = topBandDismissControls(app: app, context: context)
        outcome = .unconfirmed(payload)
      }
      return outcome
    } catch {
      logSwipe(trace.logLine(name: "error", code: String(describing: type(of: error))))
      throw error
    }
#elseif os(watchOS)
    return try performWatchBack(app: app)
#else


    return .refused(
      ErrorPayload(
        code: RunnerWireErrorCode.backSwipeNotDispatched,
        message: "visionOS has no back command",
        hint: "Press the visible back control by its ref."
      )
    )
#endif
  }

#if os(iOS)


  struct BackSwipeTrace {
    var settleSamples = 0
    var settled = false
    var maxCaptureMs = 0.0
    var stableMs: Double?
    var gestureMs: Double?
    var justBeforeToAfterMs: Double?
    var changed: NavigationVisualObservation?

    func logLine(outcome: InAppBackOutcome) -> String {
      switch outcome {
      case .performed: return logLine(name: "performed", code: nil)
      case .refused(let payload): return logLine(name: "refused", code: payload.code)
      case .unconfirmed(let payload): return logLine(name: "unconfirmed", code: payload.code)
      }
    }

    func logLine(name: String, code: String?) -> String {
      func ms(_ value: Double?) -> String { value.map { String(Int($0.rounded())) } ?? "-" }
      return [
        "outcome=\(name)",
        "code=\(code ?? "-")",
        "changed=\(changed?.logToken ?? "-")",
        "stableMs=\(ms(stableMs))",
        "justBeforeToAfterMs=\(ms(justBeforeToAfterMs))",
        "gestureMs=\(ms(gestureMs))",
        "maxCaptureMs=\(ms(maxCaptureMs))",
        "settleSamples=\(settleSamples)",
        "settled=\(settled)",
      ].joined(separator: " ")
    }
  }









  @MainActor
  private func pressNavigationBarBackButton(
    app: XCUIApplication,
    context: SynthesizedCoordinateContext
  ) throws -> InAppBackOutcome? {
    var trace = NavigationBarBackTrace()

    defer {
      NSLog("AGENT_DEVICE_RUNNER_BACK_NAVIGATION_BAR_BUTTON %@", trace.logLine)



    }
    guard navigationBarBackButtonIsReadable(context: context) else { return nil }
    let started = currentUptimeMs()
    let lookup = stillNavigationBarBackButton(
      app: app,
      geometry: context.geometry,
      deadlineMs: started + Self.navigationBarBackReadBudgetMs
    )
    trace.lookupMs = currentUptimeMs() - started
    let before: NavigationBarBackState
    let frame: CGRect
    switch lookup {
    case .still(let state, let button):
      before = state
      frame = button
    case .notFound(let found):
      trace.found = found
      return nil
    case .hung:
      trace.found = "hung"
      return .refused(Self.navigationBarBackHungLookup)
    }
    trace.found = "yes"



    switch try performSynthesizedTapGesture(app: app, x: frame.midX, y: frame.midY, context: context) {
    case .performed:
      break
    case .xctestFallback:
      _ = try performGesture(app) { try tapAt(app: app, x: frame.midX, y: frame.midY, context: context) }
    case .refused:
      return nil
    }
    trace.pressed = true
    let tapped = currentUptimeMs()
    let confirmation = navigationBarBackConfirmation(
      app: app,
      from: before,
      windowHeight: context.geometry.windowOnScreen.rect.height,
      deadlineMs: tapped + Self.navigationBarBackReadBudgetMs
    )
    trace.confirmMs = currentUptimeMs() - tapped
    trace.confirmed = confirmation.logToken
    switch confirmation {
    case .changed: return .performed
    case .unchanged: return .unconfirmed(Self.navigationBarBackUnverified)
    case .hung: return .unconfirmed(Self.navigationBarBackHungConfirmation)
    }
  }


  struct NavigationBarBackTrace {



    var found = "skipped"
    var pressed = false

    var confirmed: String?
    var lookupMs = 0.0
    var confirmMs: Double?

    var logLine: String {
      func ms(_ value: Double?) -> String { value.map { String(Int($0.rounded())) } ?? "-" }
      return [
        "found=\(found)",
        "pressed=\(pressed ? "yes" : "no")",
        "confirmed=\(confirmed ?? "-")",
        "lookupMs=\(ms(lookupMs))",
        "confirmMs=\(ms(confirmMs))",
      ].joined(separator: " ")
    }
  }













  struct NavigationBarBackState: Equatable {
    var barCount: Int
    let backButtonLabels: [String]
    let backButtonFrames: [CGRect]
    var barTitles: [String] = []

    var hasUnlabeledBackButton: Bool { backButtonLabels.contains(where: \.isEmpty) }

    func hasSameButtons(as other: NavigationBarBackState) -> Bool {
      backButtonLabels == other.backButtonLabels && backButtonFrames == other.backButtonFrames
    }



    var canShowAPop: Bool { !hasUnlabeledBackButton || barTitles.contains { !$0.isEmpty } }
  }






  static func navigationBarBackPopped(from before: NavigationBarBackState, to after: NavigationBarBackState) -> Bool {
    after.barCount != before.barCount || after.backButtonLabels != before.backButtonLabels
      || after.barTitles != before.barTitles
  }




  static let navigationBarBackReadInterval: TimeInterval = 0.05
  static let navigationBarBackReadBudgetMs = 1000.0

  static let navigationBarBackUnverified = ErrorPayload(
    code: RunnerWireErrorCode.backSwipeUnverified,
    message: "back pressed the navigation bar back button, but the navigation bar's back buttons did not change within 1 s or on one more read after it. This is an unknown outcome.",
    hint: "Take a snapshot to see where the app is."
  )

  static let navigationBarBackHungConfirmation = ErrorPayload(
    code: RunnerWireErrorCode.backSwipeUnverified,
    message: "back pressed the navigation bar back button, but an XCTest query on the navigation bar hung afterwards. This is an unknown outcome.",
    hint: "Take a snapshot to see where the app is."
  )

  static let navigationBarBackHungLookup = ErrorPayload(
    code: RunnerWireErrorCode.backSwipeNotDispatched,
    message: "back sent nothing: an XCTest query on the navigation bar hung before the back button or the swipe.",
    hint: "Take a snapshot to check that the app responds, then retry back."
  )



  enum NavigationBarBackLookup {
    case still(NavigationBarBackState, button: CGRect)
    case notFound(String)
    case hung
  }








  @MainActor
  private func stillNavigationBarBackButton(
    app: XCUIApplication,
    geometry: SurfaceGeometry,
    deadlineMs: Double
  ) -> NavigationBarBackLookup {
    let windowHeight = geometry.windowOnScreen.rect.height
    var previous: NavigationBarBackState?
    var barsRead: (state: NavigationBarBackState, bars: [NavigationBarSnapshot])?
    while true {
      let sample: NavigationBarBackSample
      switch readNavigationBarBack(
        app: app, phase: .lookup, deadlineMs: deadlineMs, windowHeight: windowHeight, knownBars: barsRead?.bars
      ) {
      case .hung: return .hung
      case .unreadable: return .notFound("unreadable")
      case .read(let read): sample = read
      }
      let candidates = sample.candidates(by: sample.bars)
      if candidates.isEmpty { return .notFound("no") }
      let current = sample.state(of: candidates, bars: nil)
      let buttonsStill = previous.map { current.hasSameButtons(as: $0) } ?? false
      if sample.barsWereRead {
        barsRead = (sample.state(of: candidates, bars: sample.bars), sample.bars)
      } else if !buttonsStill {
        barsRead = nil
      }
      if buttonsStill, let barsBefore = barsRead?.state {

        let liveDeadlineMs = currentUptimeMs() + Self.navigationBarBackReadBudgetMs
        switch liveNavigationBarBackButton(of: sample, geometry: geometry, deadlineMs: liveDeadlineMs) {
        case .hung: return .hung
        case .unreadable: return .notFound("unreadable")
        case .read(.absent(let found)): return .notFound(found)
        case .read(.found(let state, let button, let bars)):
          if state == barsBefore { return .still(state, button: button) }
          barsRead = (state, bars)
        case .read(.moving): break
        }
      }
      if currentUptimeMs() >= deadlineMs { return .notFound("moving") }
      previous = current
      sleepFor(Self.navigationBarBackReadInterval)
    }
  }


  enum NavigationBarBackLive {
    case found(NavigationBarBackState, CGRect, [NavigationBarSnapshot])
    case absent(String)
    case moving
  }



  @MainActor
  private func liveNavigationBarBackButton(
    of sample: NavigationBarBackSample,
    geometry: SurfaceGeometry,
    deadlineMs: Double
  ) -> NavigationBarBackRead<NavigationBarBackLive> {
    heldNavigationBarRead(.lookup) {
      let bars = sample.roots.flatMap { $0.descendants(matching: .navigationBar).allElementsBoundByIndex }
      guard let snapshots = barSnapshots(bars, deadlineMs: deadlineMs) else { return nil }
      let candidates = sample.candidates(by: snapshots)
      let hittable = candidates.filter { sample.buttons[$0].isHittable }
      if hittable.isEmpty { return .absent("no") }
      if hittable.count > 1 { return .absent("ambiguous") }
      let button = sample.buttons[hittable[0]].frame
      guard SnapshotGeometry.isPositiveFinite(button) else { return nil }
      let state = sample.state(of: candidates, bars: snapshots)
      if !state.canShowAPop { return .absent("unprovable") }
      return Self.navigationBarBackState(state, holdsButton: button, geometry: geometry)
        ? .found(state, button, snapshots) : .moving
    }
  }



  static func navigationBarBackState(
    _ state: NavigationBarBackState,
    holdsButton button: CGRect,
    geometry: SurfaceGeometry
  ) -> Bool {
    state.backButtonFrames.contains { frame in
      let origin = geometry.screenPoint(from: SurfacePoint<WindowContentSpace>(frame.origin)).point
      return CGRect(origin: origin, size: frame.size) == button
    }
  }

  enum NavigationBarBackConfirmation {
    case changed
    case unchanged
    case hung

    var logToken: String {
      switch self {
      case .changed: return "yes"
      case .unchanged: return "no"
      case .hung: return "hung"
      }
    }
  }






  @MainActor
  private func navigationBarBackConfirmation(
    app: XCUIApplication,
    from before: NavigationBarBackState,
    windowHeight: CGFloat,
    deadlineMs: Double
  ) -> NavigationBarBackConfirmation {
    while true {
      let isFinalRead = currentUptimeMs() >= deadlineMs
      let readDeadlineMs = isFinalRead ? Double.infinity : deadlineMs
      let phase: NavigationBarBackReadPhase = isFinalRead ? .finalConfirmation : .confirmation
      switch readNavigationBarBack(
        app: app, phase: phase, deadlineMs: readDeadlineMs, windowHeight: windowHeight, knownBars: nil
      ) {
      case .read(let after)
      where Self.navigationBarBackPopped(
        from: before, to: after.state(of: after.candidates(by: after.bars), bars: after.bars)
      ):
        return .changed
      case .hung: return .hung
      case .read, .unreadable: break
      }
      if isFinalRead { return .unchanged }
      sleepFor(min(Self.navigationBarBackReadInterval, max(0, deadlineMs - currentUptimeMs()) / 1000))
    }
  }

  @MainActor
  private func navigationBarBackButtonIsReadable(context: SynthesizedCoordinateContext) -> Bool {
    guard !context.treeUnreadable, context.accessibilityHealth != .unavailable else { return false }
    return !isSnapshotXCTestChannelPenalized(bundleId: mainOwned.bundleId)
  }




  enum NavigationBarBackReadPhase {
    case lookup
    case confirmation
    case finalConfirmation
    case dismissControlLookup
  }


  enum NavigationBarBackRead<Value> {
    case read(Value)
    case unreadable
    case hung
  }




  @MainActor
  private func heldNavigationBarRead<T>(_ phase: NavigationBarBackReadPhase, _ read: () -> T?) -> NavigationBarBackRead<T> {
    var value: T?
    let held = holdingRecordedIssues {
      value = read()





    }
    let hung = held.issues.filter { Self.isHungQueryIssueDescription($0.compactDescription) }
    hung.forEach { record($0) }
    if !hung.isEmpty { return .hung }
    guard held.issues.isEmpty, held.exceptionMessage == nil, let value else { return .unreadable }
    return .read(value)
  }




  struct NavigationBarBackSample {
    let buttons: [XCUIElement]
    let labels: [String]

    let frames: [CGRect]
    let roots: [XCUIElement]
    let bars: [NavigationBarSnapshot]
    let barsWereRead: Bool
    let windowHeight: CGFloat

    func candidates(by bars: [NavigationBarSnapshot]) -> [Int] {
      RunnerTests.backButtonCandidates(frames, barFrames: bars.map(\.frame), windowHeight: windowHeight)
    }


    func state(of candidates: [Int], bars: [NavigationBarSnapshot]?) -> NavigationBarBackState {
      let state = NavigationBarBackState(
        barCount: 0, backButtonLabels: candidates.map { labels[$0] }, backButtonFrames: candidates.map { frames[$0] })
      return bars.map { RunnerTests.addingBars($0, to: state) } ?? state
    }
  }





  @MainActor
  private func readNavigationBarBack(
    app: XCUIApplication,
    phase: NavigationBarBackReadPhase,
    deadlineMs: Double,
    windowHeight: CGFloat,
    knownBars: [NavigationBarSnapshot]?
  ) -> NavigationBarBackRead<NavigationBarBackSample> {
    guard currentUptimeMs() < deadlineMs else { return .unreadable }
    return heldNavigationBarRead(phase) {
      guard let roots = try? elementSearchRoots(root: app, litDisplayID: requestLitPanel?.displayID) else { return nil }
      let buttons = roots.flatMap {
        $0.descendants(matching: .button).matching(identifier: Self.navigationBarBackButtonIdentifier).allElementsBoundByIndex
      }
      var labels: [String] = []
      var frames: [CGRect] = []
      for button in buttons {
        guard currentUptimeMs() < deadlineMs, let snapshot = try? button.snapshot() else { return nil }
        labels.append(snapshot.label)
        frames.append(snapshot.frame)
      }
      var bars = knownBars
      if bars == nil {
        let elements = roots.flatMap { $0.descendants(matching: .navigationBar).allElementsBoundByIndex }
        bars = barSnapshots(elements, deadlineMs: deadlineMs)
      }
      guard let bars else { return nil }
      return NavigationBarBackSample(
        buttons: buttons, labels: labels, frames: frames, roots: roots, bars: bars,
        barsWereRead: knownBars == nil, windowHeight: windowHeight
      )
    }
  }






  static func backButtonBelongsToABar(_ button: CGRect, barFrames: [CGRect], windowHeight: CGFloat) -> Bool {
    barFrames.contains { bar in
      button.midX >= bar.minX && button.midX <= bar.maxX
        && button.minY >= bar.minY && button.minY <= bar.minY + windowHeight / 3
    }
  }






  static func backButtonCandidates(_ frames: [CGRect], barFrames: [CGRect], windowHeight: CGFloat) -> [Int] {
    let inside = frames.indices.filter { index in
      barFrames.contains { $0.contains(CGPoint(x: frames[index].midX, y: frames[index].midY)) }
    }
    if !inside.isEmpty { return inside }
    return frames.indices.filter {
      backButtonBelongsToABar(frames[$0], barFrames: barFrames, windowHeight: windowHeight)
    }
  }

  struct NavigationBarSnapshot {
    let frame: CGRect

    let title: String
  }


  func barSnapshots(_ bars: [XCUIElement], deadlineMs: Double) -> [NavigationBarSnapshot]? {
    var snapshots: [NavigationBarSnapshot] = []
    for bar in bars {
      guard currentUptimeMs() < deadlineMs, let snapshot = try? bar.snapshot() else { return nil }
      snapshots.append(
        NavigationBarSnapshot(frame: snapshot.frame, title: snapshot.identifier.isEmpty ? snapshot.label : snapshot.identifier))
    }
    return snapshots
  }


  static func addingBars(_ bars: [NavigationBarSnapshot], to state: NavigationBarBackState) -> NavigationBarBackState {
    var state = state
    state.barCount = bars.count
    if state.hasUnlabeledBackButton { state.barTitles = bars.map(\.title) }
    return state
  }



  static let dismissControlWords: Set<String> = ["back", "close", "cancel"]




  static func selectorText(_ text: String) -> String {
    text.split(whereSeparator: \.isWhitespace).joined(separator: " ").lowercased()
  }


  static func isDismissControlName(_ name: String) -> Bool {
    let word = selectorText(name)
    return dismissControlWords.contains(word) || word == "xmark" || word.hasPrefix("xmark.")
  }




  static let dismissControlPredicate: NSPredicate = {
    let names = dismissControlWords.sorted() + ["xmark"]
    let clauses = names.flatMap { _ in ["label CONTAINS[c] %@", "identifier CONTAINS[c] %@"] } + ["label == ''"]
    return NSPredicate(format: clauses.joined(separator: " OR "), argumentArray: names.flatMap { [$0, $0] })
  }()




  struct TopBandButton {
    let label: String
    let identifier: String
    let frame: CGRect
  }


  struct ButtonName {
    let label: String
    let identifier: String
  }



  static func isTopNavigationControlFrame(_ candidate: CGRect, in window: CGRect) -> Bool {
    guard SnapshotGeometry.isPositiveFinite(candidate), SnapshotGeometry.isPositiveFinite(window) else {
      return false
    }
    let maxY = window.minY + min(max(window.height * 0.22, 96), 180)
    return candidate.midY >= window.minY && candidate.midY <= maxY
  }




  static func dismissControlRoots<Root>(resolvedWindow: Root?, searchRoots: [Root]) -> [Root] {
    resolvedWindow.map { [$0] } ?? searchRoots
  }







  static func dismissControls(
    _ buttons: [TopBandButton],
    everyButton: [ButtonName],
    window: CGRect,
    isHittable: (Int) -> Bool
  ) -> [DismissControlPayload] {
    buttons.indices.compactMap { index in
      let button = buttons[index]
      guard button.identifier != navigationBarBackButtonIdentifier,
        isTopNavigationControlFrame(button.frame, in: window) else { return nil }
      let pressBy: DismissControlPayload.PressBy
      if isDismissControlName(button.label) {
        pressBy = .label
      } else if isDismissControlName(button.identifier) {
        pressBy = .identifier
      } else {
        return nil
      }
      func attribute(_ name: ButtonName) -> String { selectorText(pressBy == .label ? name.label : name.identifier) }
      let text = attribute(ButtonName(label: button.label, identifier: button.identifier))
      let matches = everyButton.filter { attribute($0) == text }
      guard matches.count == 1, isHittable(index) else { return nil }
      return DismissControlPayload(
        label: button.label, identifier: button.identifier.isEmpty ? nil : button.identifier, pressBy: pressBy)
    }
  }







  @MainActor
  private func topBandDismissControls(
    app: XCUIApplication,
    context: SynthesizedCoordinateContext
  ) -> [DismissControlPayload]? {
    guard navigationBarBackButtonIsReadable(context: context) else { return nil }
    let deadlineMs = currentUptimeMs() + Self.navigationBarBackReadBudgetMs

    let window = CGRect(origin: .zero, size: context.geometry.windowOnScreen.rect.size)
    let read = heldNavigationBarRead(.dismissControlLookup) { () -> [DismissControlPayload]? in
      guard let searchRoots = try? elementSearchRoots(root: app, litDisplayID: requestLitPanel?.displayID) else {
        return nil
      }
      @MainActor func buttons(under roots: [XCUIElement]) -> (elements: [XCUIElement], buttons: [TopBandButton])? {
        let elements = roots.flatMap {
          $0.descendants(matching: .button).matching(Self.dismissControlPredicate).allElementsBoundByIndex
        }
        var buttons: [TopBandButton] = []
        for element in elements {
          guard currentUptimeMs() < deadlineMs, let snapshot = try? element.snapshot() else { return nil }
          let node = evaluateSnapshot(snapshot)
          buttons.append(TopBandButton(label: node.label, identifier: node.identifier, frame: snapshot.frame))
        }
        return (elements, buttons)
      }
      guard let every = buttons(under: searchRoots) else { return nil }
      let roots = Self.dismissControlRoots(resolvedWindow: context.resolvedWindow, searchRoots: searchRoots)
      guard let listed = context.resolvedWindow == nil ? every : buttons(under: roots) else { return nil }
      let everyButton = every.buttons.map { ButtonName(label: $0.label, identifier: $0.identifier) }
      return Self.dismissControls(listed.buttons, everyButton: everyButton, window: window) {
        listed.elements[$0].isHittable
      }
    }
    guard case .read(let controls) = read, !controls.isEmpty else { return nil }
    return controls
  }

  @MainActor
  private func verifiedBackSwipe(
    app: XCUIApplication,
    context: SynthesizedCoordinateContext,
    trace: inout BackSwipeTrace
  ) throws -> InAppBackOutcome {


    let dispatchGesture: @MainActor () throws -> TouchDispatch
    switch try prepareBackGesture(app: app, context: context) {
    case .ready(let dispatch): dispatchGesture = dispatch
    case .notSent(let message, let hint):
      return .refused(ErrorPayload(code: RunnerWireErrorCode.backSwipeNotDispatched, message: message, hint: hint))
    }
    let before: SettledBackSample
    switch settledBackVisualState(app: app, context: context, trace: &trace) {
    case .success(let settled): before = settled
    case .failure(let refusal): return .refused(Self.backScreenRefusal(refusal))
    }
    let justBeforeMs = before.sampledMs
    trace.stableMs = justBeforeMs - before.stableSinceMs
    let dispatch = try dispatchGesture()
    trace.gestureMs = currentUptimeMs() - justBeforeMs
    if let refusal = Self.backGestureRefusal(dispatch) {
      return refusal
    }
    guard before.settled else {
      return .unconfirmed(
        Self.backSwipeUnverified(
          because: "the app's screen was already changing on its own",
          hint: "Take a snapshot to see where the app is."
        )
      )
    }
    sleepFor(Self.backSwipeVerificationDelay)
    let after = timedBackCapture(app: app, context: context, trace: &trace)
    let afterMs = currentUptimeMs()
    trace.justBeforeToAfterMs = afterMs - justBeforeMs
    let observation = Self.navigationVisualObservation(before: .success(before.sample), after: after)
    trace.changed = observation
    guard Self.backSwipeGapIsCovered(
      stableSinceMs: before.stableSinceMs,
      justBeforeMs: justBeforeMs,
      afterMs: afterMs
    ) else {
      return .unconfirmed(
        Self.backSwipeUnverified(
          because: "the swipe took longer than the screen had been still before it",
          hint: "Take a snapshot to see where the app is."
        )
      )
    }
    return Self.backSwipeOutcome(observation: observation)
  }


  @MainActor
  private func timedBackCapture(
    app: XCUIApplication,
    context: SynthesizedCoordinateContext,
    trace: inout BackSwipeTrace
  ) -> Result<Data, RunnerAppScreenCaptureFailure> {
    let started = currentUptimeMs()
    let sample = captureBackVisualState(app: app, context: context)
    trace.maxCaptureMs = max(trace.maxCaptureMs, currentUptimeMs() - started)
    return sample
  }

  static func backGestureRefusal(_ dispatch: TouchDispatch) -> InAppBackOutcome? {
    switch dispatch {
    case .sent:
      return nil
    case .notSent(let message, let hint):
      return .refused(ErrorPayload(code: RunnerWireErrorCode.backSwipeNotDispatched, message: message, hint: hint))
    case .interrupted(let message, _):
      return .unconfirmed(
        backSwipeUnverified(
          because: "it was cut short after it touched down (\(message))",
          hint: "Check the screen with snapshot before you retry; the swipe may already have navigated."
        )
      )
    }
  }
#endif


  static func backScreenRefusal(_ refusal: RunnerAppScreenCaptureFailure) -> ErrorPayload {
    ErrorPayload(
      code: refusal.rawValue,
      message: "back did not swipe: the app's screen could not be sampled to verify it.",
      hint: refusal.hint
    )
  }




  static let macOSInAppBackControlRefusal = ErrorPayload(
    code: RunnerWireErrorCode.inAppBackControlUnavailable,
    message: "in-app back control is not available",
    hint: "Press the app's visible back control by its ref."
  )

#if os(iOS)


  struct SettledBackSample {
    let sample: Data
    let stableSinceMs: Double
    let sampledMs: Double
    let settled: Bool
  }




  @MainActor
  private func settledBackVisualState(
    app: XCUIApplication,
    context: SynthesizedCoordinateContext,
    trace: inout BackSwipeTrace
  ) -> Result<SettledBackSample, RunnerAppScreenCaptureFailure> {
    let started = currentUptimeMs()
    var runStart: (sample: Data, ms: Double)?
    while true {
      if trace.settleSamples > 0 { sleepFor(Self.backSwipeSettleSampleInterval) }
      trace.settleSamples += 1
      let sample: Data
      switch timedBackCapture(app: app, context: context, trace: &trace) {
      case .failure(let refusal): return .failure(refusal)
      case .success(let captured): sample = captured
      }
      let now = currentUptimeMs()
      let start = runStart.flatMap { Self.visualSamplesDiffer($0.sample, sample) ? nil : $0 } ?? (sample: sample, ms: now)
      runStart = start
      if now - start.ms >= Self.backSwipeRequiredStillMs(maxCaptureMs: trace.maxCaptureMs) {
        trace.settled = true
        return .success(SettledBackSample(sample: sample, stableSinceMs: start.ms, sampledMs: now, settled: true))
      }
      if now - started >= Self.backSwipeSettleBudgetMs(maxCaptureMs: trace.maxCaptureMs) {
        return .success(SettledBackSample(sample: sample, stableSinceMs: start.ms, sampledMs: now, settled: false))
      }
    }
  }
#endif






  private func captureBackVisualState(
    app: XCUIApplication,
    context: SynthesizedCoordinateContext
  ) -> Result<Data, RunnerAppScreenCaptureFailure> {
#if os(iOS)
    return Self.navigationVisualSample(

      from: context.resolvedWindow == nil && requestLitPanel == nil
        ? captureSoleAppScreen(app: app)
        : captureResolvedAppScreen(app: app, litPanel: requestLitPanel),
      encoding: { runnerCGImage(from: $0.image).flatMap(Self.visualGrid) }
    )
#else
    return .failure(.unresolvedScreen)
#endif
  }




  static func navigationVisualSample(
    from captured: Result<CapturedAppScreen, RunnerAppScreenCaptureFailure>,
    encoding: (CapturedAppScreen) -> Data?
  ) -> Result<Data, RunnerAppScreenCaptureFailure> {
    captured.flatMap { screen in
      guard let png = encoding(screen) else { return .failure(.unrenderableImage) }
      return .success(png)
    }
  }

  static let visualGridSize = (width: 48, height: 96)






  static let backCompareTopRowsIgnored = 7
  static let visualCellTolerance = 24
  static let visualChangedCellFraction = 0.01




  static func visualGrid(of image: CGImage) -> Data? {
    let (width, height) = visualGridSize
    var cells = [UInt8](repeating: 0, count: width * height)
    let drawn = cells.withUnsafeMutableBytes { buffer -> Bool in
      guard let context = CGContext(
        data: buffer.baseAddress, width: width, height: height, bitsPerComponent: 8,
        bytesPerRow: width, space: CGColorSpaceCreateDeviceGray(),
        bitmapInfo: CGImageAlphaInfo.none.rawValue
      ) else { return false }
      context.interpolationQuality = .medium
      context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
      return true
    }
    return drawn ? Data(cells) : nil
  }



  static func visualSamplesDiffer(_ lhs: Data, _ rhs: Data) -> Bool {
    guard lhs.count == rhs.count else { return true }
    let ignored = min(lhs.count, backCompareTopRowsIgnored * visualGridSize.width)
    let compared = zip(lhs.dropFirst(ignored), rhs.dropFirst(ignored))
    let moved = compared.reduce(0) { count, pair in
      abs(Int(pair.0) - Int(pair.1)) > visualCellTolerance ? count + 1 : count
    }
    return Double(moved) > Double(lhs.count - ignored) * visualChangedCellFraction
  }






  static func backSwipeGapIsCovered(stableSinceMs: Double, justBeforeMs: Double, afterMs: Double) -> Bool {
    afterMs - justBeforeMs <= justBeforeMs - stableSinceMs
  }



  static func backSwipeOutcome(observation: NavigationVisualObservation) -> InAppBackOutcome {
    switch observation {
    case .changed:
      return .performed
    case .unchanged:
      return .unconfirmed(
        ErrorPayload(
          code: RunnerWireErrorCode.backSwipeNoChange,
          message: "The back swipe changed nothing.",
          hint: "Press the visible back or close control by its ref from a fresh snapshot."
        )
      )
    case .unobserved(let refusal):
      return .unconfirmed(
        backSwipeUnverified(because: "the app's screen could not be sampled afterwards", hint: refusal.hint)
      )
    }
  }

  static func backSwipeUnverified(because reason: String, hint: String?) -> ErrorPayload {
    ErrorPayload(
      code: RunnerWireErrorCode.backSwipeUnverified,
      message: "The back swipe ran, but \(reason). This is an unknown outcome.",
      hint: hint
    )
  }

  static func navigationVisualObservation(
    before: Result<Data, RunnerAppScreenCaptureFailure>,
    after: Result<Data, RunnerAppScreenCaptureFailure>
  ) -> NavigationVisualObservation {
    switch (before, after) {
    case (.success(let before), .success(let after)):
      return visualSamplesDiffer(before, after) ? .changed : .unchanged

    case (_, .failure(let refusal)):
      return .unobserved(refusal: refusal)
    case (.failure(let refusal), _):
      return .unobserved(refusal: refusal)
    }
  }

  private func macOSNavigationBackElement(app: XCUIApplication) -> XCUIElement? {
    let predicate = NSPredicate(
      format: "identifier == %@ OR label == %@",
      "go back",
      "Back"
    )
    let element = app.descendants(matching: .any).matching(predicate).firstMatch
    return element.exists ? element : nil
  }
}
