import AppKit
import QuartzCore
import AlignerCore

enum QuickSwitchCommitSource: String {
    case keyboard
    case mouse
}

@MainActor
final class QuickSwitchRootView: NSView {
    private let backdropBlurView = NSVisualEffectView()
    private let layerHostView = NSView()
    private let backgroundLayer = CAGradientLayer()
    private let safeAreaFillLayer = CALayer()
    private let glassLayer = CALayer()
    private let laneLayer = CALayer()
    private let spaceLaneContentLayer = CALayer()
    private let shelfLayer = CALayer()
    private let appShelfContentLayer = CALayer()
    private let waterfallLayer = CALayer()
    private let waterfallContentLayer = CALayer()
    private let appIconProvider: any AppIconProviderProtocol = WorkspaceAppIconProvider()
    private let skeletonThumbnailProvider = NativeSkeletonThumbnailProvider(size: NSSize(width: 160, height: 96))
    private var screenshotSourcesByWindowID: [UInt32: ScreenshotResolutionSource] = [:]
    private var screenshotSkippedReasonsByWindowID: [UInt32: String] = [:]
    private var currentViewModel: QuickSwitchViewModel?
    private var spaceLaneSegments: [SpaceLaneSegmentLayers] = []
    private var spaceLaneContentWidth: CGFloat = 0
    private var spaceLaneScrollOffset: CGFloat = 0
    private var appShelfItems: [AppShelfItemLayers] = []
    private var appShelfLayout = AppShelfLayout(rows: 0, iconSize: AppShelfMetrics.normalIconSize)
    private var appShelfContentWidth: CGFloat = 0
    private var appShelfScrollOffset: CGFloat = 0
    private var appShelfTrackingArea: NSTrackingArea?
    private var hoveredAppGroupIndex: Int?
    private var hoveredWindowID: UInt32?
    private var hoveredSpaceID: UInt64?
    private var hoveredSpaceLaneID: UInt64?
    private var focusedSpaceID: UInt64?
    private var debugHoveredAppGroupIndex: Int?
    private var waterfallColumns: [WaterfallColumnLayers] = []
    private var waterfallContentWidth: CGFloat = 0
    private var waterfallScrollOffset: CGFloat = 0
    private var waterfallColumnScrollOffsets: [Int: CGFloat] = [:]
    private var currentSelection: QuickSwitchSelection?
    private var columnSelectionHistory: [Int: Int] = [:]
    private var keyboardCommandsApplied: [String] = []
    private var lastKeyboardCommand: String?
    private var tabIgnoredCount = 0
    private var lastCommittedSelection: QuickSwitchSelection?
    private var lastCommitSource: QuickSwitchCommitSource?
    private var mouseCommandsApplied: [String] = []
    private var lastMouseCommand: String?
    private var lastClickedAppGroupIndex: Int?
    private var lastAppShelfClickChangedSelection: Bool?
    private var lastClickedWindowID: UInt32?
    private var lastSpaceFocusedAppGroupIndex: Int?
    private var lastSpaceLaneClickSpaceID: UInt64?
    private var lastAppShelfScrollSyncedAppGroupIndex: Int?
    private var firstFrameMeasurementStart: CFTimeInterval?
    private var firstFrameLatencyMilliseconds: [Double] = []
    private var keyboardResponseLatencyMilliseconds: [Double] = []
    private var mouseResponseLatencyMilliseconds: [Double] = []
    private var hoverResponseLatencyMilliseconds: [Double] = []
    var onEscape: (() -> Void)?
    var onCommitSelection: ((QuickSwitchSelection, QuickSwitchCommitSource) -> Void)?

    private struct SpaceLaneSegmentLayers {
        let space: QuickSwitchSpaceViewModel
        let containerLayer: CALayer
        let labelLayer: CATextLayer
        let countLayer: CATextLayer
        let appLayer: CATextLayer
        let windowBlocks: [CALayer]
        let fullscreenMarkerLayer: CALayer?
    }

    private struct AppShelfItemLayers {
        let item: QuickSwitchAppShelfItemViewModel
        let containerLayer: CALayer
        let backgroundLayer: CALayer
        let iconLayer: CALayer
        let labelLayer: CATextLayer
        let badgeLayer: CATextLayer
        let selectedIndicatorLayer: CALayer
    }

    private struct AppShelfLayout {
        let rows: Int
        let iconSize: CGFloat
    }

    private struct WaterfallColumnLayers {
        let column: QuickSwitchWaterfallColumnViewModel
        let containerLayer: CALayer
        let headerLayer: CALayer
        let appNameLayer: CATextLayer
        let countLayer: CATextLayer
        let cards: [WaterfallCardLayers]
    }

    private struct WaterfallCardLayers {
        let item: QuickSwitchWindowCardViewModel
        let containerLayer: CALayer
        let titleLayer: CATextLayer
        let metaLayer: CATextLayer
        let thumbnailLayer: CALayer
        let appIconLayer: CALayer
        let stateLayer: CATextLayer
        let shineLayer: CAGradientLayer
    }

    private enum AppShelfMetrics {
        static let normalIconSize: CGFloat = 56
        static let hoverIconSize: CGFloat = 68
        static let selectedIconSize: CGFloat = 68
        static let minIconSize: CGFloat = 36
        static let normalGap: CGFloat = 16
        static let minGap: CGFloat = 8
        static let maxRows = 2
    }

    private enum RootLayoutMetrics {
        static let horizontalMargin: CGFloat = 24
        static let topContentMargin: CGFloat = 24
        static let shelfGap: CGFloat = 16
        static let waterfallTopGap: CGFloat = 14
        static let bottomMargin: CGFloat = 34
    }

    private enum WaterfallMetrics {
        static let gap: CGFloat = 16
        static let columnWidth: CGFloat = 252
        static let columnMinWidth: CGFloat = 220
        static let columnMaxWidth: CGFloat = 292
        static let columnPadding: CGFloat = 12
        static let headerHeight: CGFloat = 34
        static let cardHeight: CGFloat = 118
        static let cardGap: CGFloat = 12
        static let revealPadding: CGFloat = 24
    }

    private enum WaterfallHorizontalIntent {
        case reveal
        case alignWithAppShelf(animated: Bool)
    }

    private enum WaterfallAlignmentMetrics {
        static let tolerance: CGFloat = 1
        static let animationDuration: CFTimeInterval = 0.18
        static let animationTimingName = CAMediaTimingFunctionName.easeOut
    }

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        setupBackdropBlurView()
        setupLayerHostView()
        wantsLayer = true
        setupLayers()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupBackdropBlurView()
        setupLayerHostView()
        wantsLayer = true
        setupLayers()
    }

    override var acceptsFirstResponder: Bool {
        true
    }

    override func updateTrackingAreas() {
        super.updateTrackingAreas()

        if let appShelfTrackingArea {
            removeTrackingArea(appShelfTrackingArea)
        }

        let trackingArea = NSTrackingArea(
            rect: bounds,
            options: [.activeInKeyWindow, .mouseMoved, .mouseEnteredAndExited, .inVisibleRect],
            owner: self,
            userInfo: nil
        )
        addTrackingArea(trackingArea)
        appShelfTrackingArea = trackingArea
    }

    override func layout() {
        super.layout()
        backdropBlurView.frame = bounds
        layerHostView.frame = bounds
        layoutLayers()
    }

    override func keyDown(with event: NSEvent) {
        switch event.keyCode {
        case TriggerKeyCode.escape where Self.shouldDismissOnEscape(event):
            onEscape?()
        case TriggerKeyCode.leftArrow:
            performKeyboardCommand("left")
        case TriggerKeyCode.rightArrow:
            performKeyboardCommand("right")
        case TriggerKeyCode.upArrow:
            performKeyboardCommand("up")
        case TriggerKeyCode.downArrow:
            performKeyboardCommand("down")
        case TriggerKeyCode.returnKey, TriggerKeyCode.keypadEnter:
            performKeyboardCommand("enter")
        case TriggerKeyCode.tab:
            performKeyboardCommand("tab")
        default:
            super.keyDown(with: event)
        }
    }

    override func scrollWheel(with event: NSEvent) {
        let dominantDelta = abs(event.scrollingDeltaX) >= abs(event.scrollingDeltaY)
            ? event.scrollingDeltaX
            : event.scrollingDeltaY

        if shouldScrollSpaceLane(for: event), spaceLaneMaxScrollOffset > 0 {
            spaceLaneScrollOffset = clampedSpaceLaneOffset(spaceLaneScrollOffset - dominantDelta)
            needsLayout = true
            return
        }

        if shouldScrollAppShelf(for: event), appShelfMaxScrollOffset > 0 {
            let previousOffset = appShelfScrollOffset
            appShelfScrollOffset = clampedAppShelfOffset(appShelfScrollOffset - dominantDelta)
            syncWaterfallToVisibleAppShelfItem(previousOffset: previousOffset)
            needsLayout = true
            return
        }

        if shouldScrollWaterfall(for: event) {
            if abs(event.scrollingDeltaX) >= abs(event.scrollingDeltaY), waterfallAlignmentScrollable {
                waterfallScrollOffset = clampedWaterfallAlignmentOffset(waterfallScrollOffset - event.scrollingDeltaX)
                needsLayout = true
                return
            }

        let appGroupIndex = waterfallColumn(at: event.locationInWindow)?.column.appGroupIndex
                ?? effectiveSelection?.appGroupIndex
                ?? waterfallColumns.first?.column.appGroupIndex
            if let appGroupIndex, waterfallMaxVerticalScrollOffset(for: appGroupIndex) > 0 {
                let currentOffset = waterfallColumnScrollOffsets[appGroupIndex] ?? 0
                waterfallColumnScrollOffsets[appGroupIndex] = clampedWaterfallColumnOffset(
                    currentOffset - event.scrollingDeltaY,
                    appGroupIndex: appGroupIndex
                )
                needsLayout = true
                return
            }
        }

        super.scrollWheel(with: event)
    }

    override func mouseMoved(with event: NSEvent) {
        guard debugHoveredAppGroupIndex == nil else { return }

        if let segment = spaceLaneSegment(at: event.locationInWindow) {
            hoverSpaceLaneSegment(segment)
            return
        }

        if let card = waterfallCard(at: event.locationInWindow) {
            hoveredSpaceLaneID = nil
            updateHoverState(
                appGroupIndex: card.item.appGroupIndex,
                windowID: card.item.window.id,
                spaceID: card.item.primarySpaceID
            )
            return
        }

        if let item = appShelfItem(at: event.locationInWindow) {
            hoveredSpaceLaneID = nil
            updateHoverState(
                appGroupIndex: item.item.appGroupIndex,
                windowID: nil,
                spaceID: nil,
                alignsWaterfallWithAppShelf: true
            )
            return
        }

        hoveredSpaceLaneID = nil
        updateHoverState(appGroupIndex: nil, windowID: nil, spaceID: nil)
    }

    override func mouseExited(with event: NSEvent) {
        guard debugHoveredAppGroupIndex == nil else { return }
        hoveredSpaceLaneID = nil
        updateHoverState(appGroupIndex: nil, windowID: nil, spaceID: nil)
    }

    override func mouseDown(with event: NSEvent) {
        if let card = waterfallCard(at: event.locationInWindow) {
            clickWindowCard(card)
            return
        }

        if let segment = spaceLaneSegment(at: event.locationInWindow) {
            clickSpaceLaneSegment(segment)
            return
        }

        if let item = appShelfItem(at: event.locationInWindow) {
            clickAppShelfItem(item)
            return
        }

        DevelopmentDiagnostics.log("quickSwitch.view.mouseDown.miss", [
            "x": event.locationInWindow.x,
            "y": event.locationInWindow.y,
            "bounds": NSStringFromRect(bounds)
        ])
        super.mouseDown(with: event)
    }

    func setDebugHoveredAppGroupIndex(_ index: Int?) {
        debugHoveredAppGroupIndex = index
        hoveredAppGroupIndex = index
        hoveredWindowID = nil
        hoveredSpaceID = nil
        hoveredSpaceLaneID = nil
        needsLayout = true
    }

    func performDebugKeyboardCommands(_ commands: [String]) {
        guard !commands.isEmpty else { return }

        layoutSubtreeIfNeeded()
        for command in commands {
            let measurementStart = CACurrentMediaTime()
            performKeyboardCommand(command)
            layoutSubtreeIfNeeded()
            CATransaction.flush()
            keyboardResponseLatencyMilliseconds.append(milliseconds(since: measurementStart))
        }
    }

    func performDebugMouseCommands(_ commands: [String]) {
        guard !commands.isEmpty else { return }

        layoutSubtreeIfNeeded()
        for command in commands {
            let measurementStart = CACurrentMediaTime()
            performMouseCommand(command)
            layoutSubtreeIfNeeded()
            CATransaction.flush()
            let elapsed = milliseconds(since: measurementStart)
            mouseResponseLatencyMilliseconds.append(elapsed)
            if isHoverCommand(command) {
                hoverResponseLatencyMilliseconds.append(elapsed)
            }
        }
    }

    func beginPerformanceFirstFrameMeasurement() {
        firstFrameMeasurementStart = CACurrentMediaTime()
    }

    func recordPerformanceFirstFrameIfNeeded() {
        guard let firstFrameMeasurementStart else { return }

        layoutSubtreeIfNeeded()
        CATransaction.flush()
        firstFrameLatencyMilliseconds.append(milliseconds(since: firstFrameMeasurementStart))
        self.firstFrameMeasurementStart = nil
    }

    func resetPerformanceMeasurements() {
        firstFrameMeasurementStart = nil
        firstFrameLatencyMilliseconds = []
        keyboardResponseLatencyMilliseconds = []
        mouseResponseLatencyMilliseconds = []
        hoverResponseLatencyMilliseconds = []
    }

    func applyScreenshot(_ resolution: ScreenshotResolution, for windowID: UInt32) {
        screenshotSkippedReasonsByWindowID[windowID] = nil
        screenshotSourcesByWindowID[windowID] = resolution.source

        guard let card = waterfallCardsByWindowID()[windowID] else { return }
        card.thumbnailLayer.contents = resolution.image
        if case .realScreenshot = resolution.source {
            card.shineLayer.opacity = card.item.window.id == effectiveSelection?.windowID ? 1 : 0
        }
        needsLayout = true
    }

    func markScreenshotNotRequested(for windowID: UInt32, reason: String) {
        screenshotSourcesByWindowID[windowID] = nil
        screenshotSkippedReasonsByWindowID[windowID] = reason
        needsLayout = true
    }

    func markScreenshotsNotRequested(for viewModel: QuickSwitchViewModel, reason: String) {
        for window in viewModel.waterfallColumns.flatMap({ $0.windows.map(\.window) }) {
            markScreenshotNotRequested(for: window.id, reason: reason)
        }
    }

    func apply(viewModel: QuickSwitchViewModel?) {
        currentViewModel = viewModel
        screenshotSourcesByWindowID = [:]
        screenshotSkippedReasonsByWindowID = [:]
        currentSelection = viewModel?.initialSelection
        columnSelectionHistory = [:]
        keyboardCommandsApplied = []
        lastKeyboardCommand = nil
        tabIgnoredCount = 0
        lastCommittedSelection = nil
        lastCommitSource = nil
        mouseCommandsApplied = []
        lastMouseCommand = nil
        lastClickedAppGroupIndex = nil
        lastAppShelfClickChangedSelection = nil
        lastClickedWindowID = nil
        lastSpaceFocusedAppGroupIndex = nil
        lastSpaceLaneClickSpaceID = nil
        lastAppShelfScrollSyncedAppGroupIndex = nil
        hoveredWindowID = nil
        hoveredSpaceID = nil
        hoveredSpaceLaneID = nil
        focusedSpaceID = nil
        if debugHoveredAppGroupIndex == nil {
            hoveredAppGroupIndex = nil
        } else {
            hoveredAppGroupIndex = debugHoveredAppGroupIndex
        }
        if let currentSelection {
            columnSelectionHistory[currentSelection.appGroupIndex] = currentSelection.windowIndex
        }
        rebuildSpaceLaneSegments()
        rebuildAppShelfItems()
        rebuildWaterfallColumns()
        needsLayout = true
        ensureCurrentSelectionVisible(horizontalIntent: .alignWithAppShelf(animated: false))
        needsLayout = true
    }

    func reportDictionary() -> [String: Any] {
        layoutSubtreeIfNeeded()
        let firstFrameP95 = percentile95(firstFrameLatencyMilliseconds)
        let keyboardP95 = percentile95(keyboardResponseLatencyMilliseconds)
        let mouseP95 = percentile95(mouseResponseLatencyMilliseconds)
        let hoverP95 = percentile95(hoverResponseLatencyMilliseconds)
        let firstFrameGatePassed = firstFrameP95.map { $0 < 150 } ?? false
        let keyboardGatePassed = keyboardP95.map { $0 < 50 } ?? false
        let hoverGatePassed = hoverP95.map { $0 <= 32 } ?? false

        return [
            "viewClass": String(describing: Self.self),
            "isLayerBacked": wantsLayer,
            "bounds": dictionary(from: bounds),
            "safeAreaTopInset": Double(topSafeAreaInset),
            "safeAreaFillFrame": dictionary(from: safeAreaFillLayer.frame),
            "glassFrame": dictionary(from: glassLayer.frame),
            "glassCornerRadius": Double(glassLayer.cornerRadius),
            "glassBorderWidth": Double(glassLayer.borderWidth),
            "glassShadowOpacity": Double(glassLayer.shadowOpacity),
            "spaceLaneFrame": dictionary(from: laneLayer.frame),
            "spaceLaneContentWidth": Double(spaceLaneContentWidth),
            "spaceLaneVisibleWidth": Double(laneLayer.bounds.width),
            "spaceLaneMaxScrollOffset": Double(spaceLaneMaxScrollOffset),
            "spaceLaneScrollable": spaceLaneMaxScrollOffset > 0,
            "spaceLaneSegmentCount": spaceLaneSegments.count,
            "spaceLaneLabels": currentViewModel?.displays.flatMap { $0.spaces.map(\.label) } ?? [],
            "spaceLaneSegments": spaceLaneSegmentReports(),
            "spaceLaneHoveredSpaceID": hoveredSpaceLaneID ?? NSNull(),
            "spaceLaneFocusedSpaceID": focusedSpaceID ?? NSNull(),
            "activeSpaceFocusID": activeSpaceFocusID ?? NSNull(),
            "spaceFocusAppGroupIndexes": spaceFocusedAppGroupIndexes(),
            "lastSpaceFocusedAppGroupIndex": lastSpaceFocusedAppGroupIndex ?? NSNull(),
            "lastSpaceLaneClickSpaceID": lastSpaceLaneClickSpaceID ?? NSNull(),
            "lastAppShelfScrollSyncedAppGroupIndex": lastAppShelfScrollSyncedAppGroupIndex ?? NSNull(),
            "spaceLaneCurrentLabels": currentViewModel?.displays.flatMap { display in
                display.spaces.filter(\.isCurrent).map(\.label)
            } ?? [],
            "spaceLaneFullscreenLabels": currentViewModel?.displays.flatMap { display in
                display.spaces.filter { $0.type == .fullscreen }.map(\.label)
            } ?? [],
            "appShelfFrame": dictionary(from: shelfLayer.frame),
            "appShelfContentWidth": Double(appShelfContentWidth),
            "appShelfVisibleWidth": Double(shelfLayer.bounds.width),
            "appShelfScrollOffset": Double(appShelfScrollOffset),
            "appShelfMaxScrollOffset": Double(appShelfMaxScrollOffset),
            "appShelfScrollable": appShelfMaxScrollOffset > 0,
            "appShelfItemCount": appShelfItems.count,
            "appShelfNames": appShelfItems.map(\.item.app.name),
            "appShelfHoveredIndex": effectiveHoveredAppGroupIndex ?? NSNull(),
            "appShelfRows": appShelfLayout.rows,
            "appShelfMaxRows": AppShelfMetrics.maxRows,
            "appShelfIconSize": Double(appShelfLayout.iconSize),
            "appShelfNormalIconSize": Double(AppShelfMetrics.normalIconSize),
            "appShelfHoverIconSize": Double(AppShelfMetrics.hoverIconSize),
            "appShelfSelectedIconSize": Double(AppShelfMetrics.selectedIconSize),
            "appShelfMinIconSize": Double(AppShelfMetrics.minIconSize),
            "appShelfItems": appShelfItemReports(),
            "waterfallFrame": dictionary(from: waterfallLayer.frame),
            "waterfallContentWidth": Double(waterfallContentWidth),
            "waterfallVisibleWidth": Double(waterfallLayer.bounds.width),
            "waterfallScrollOffset": Double(waterfallScrollOffset),
            "waterfallMaxScrollOffset": Double(waterfallMaxScrollOffset),
            "waterfallAlignmentMinScrollOffset": Double(waterfallAlignmentScrollRange.lowerBound),
            "waterfallAlignmentMaxScrollOffset": Double(waterfallAlignmentScrollRange.upperBound),
            "waterfallScrollable": waterfallAlignmentScrollable,
            "waterfallColumnCount": waterfallColumns.count,
            "waterfallColumnNames": waterfallColumns.map(\.column.app.name),
            "waterfallClipsToBounds": waterfallLayer.masksToBounds,
            "waterfallColumns": waterfallColumnReports(),
            "appColumnAlignmentReports": appColumnAlignmentReports(),
            "waterfallAlignmentTolerance": Double(WaterfallAlignmentMetrics.tolerance),
            "waterfallAlignmentAnimationDurationMilliseconds": Double(WaterfallAlignmentMetrics.animationDuration * 1_000),
            "waterfallAlignmentAnimationTimingName": "easeOut",
            "reduceMotionEffective": NSWorkspace.shared.accessibilityDisplayShouldReduceMotion,
            "selectedAppGroupIndex": effectiveSelection?.appGroupIndex ?? NSNull(),
            "selectedWindowIndex": effectiveSelection?.windowIndex ?? NSNull(),
            "selectedWindowID": effectiveSelection?.windowID ?? NSNull(),
            "keyboardCommandsApplied": keyboardCommandsApplied,
            "lastKeyboardCommand": lastKeyboardCommand ?? NSNull(),
            "tabIgnoredCount": tabIgnoredCount,
            "lastCommittedAppGroupIndex": lastCommittedSelection?.appGroupIndex ?? NSNull(),
            "lastCommittedWindowIndex": lastCommittedSelection?.windowIndex ?? NSNull(),
            "lastCommittedWindowID": lastCommittedSelection?.windowID ?? NSNull(),
            "lastCommitSource": lastCommitSource?.rawValue ?? NSNull(),
            "hoveredAppGroupIndex": effectiveHoveredAppGroupIndex ?? NSNull(),
            "hoveredWindowID": hoveredWindowID ?? NSNull(),
            "hoveredSpaceID": hoveredSpaceID ?? NSNull(),
            "mouseCommandsApplied": mouseCommandsApplied,
            "lastMouseCommand": lastMouseCommand ?? NSNull(),
            "lastClickedAppGroupIndex": lastClickedAppGroupIndex ?? NSNull(),
            "lastAppShelfClickChangedSelection": lastAppShelfClickChangedSelection ?? NSNull(),
            "lastClickedWindowID": lastClickedWindowID ?? NSNull(),
            "columnSelectionHistory": columnSelectionHistoryReports(),
            "screenshotEligibleCount": screenshotEligibleWindows.count,
            "screenshotResolvedCount": screenshotSourcesByWindowID.count,
            "screenshotPendingCount": screenshotPendingWindows.count,
            "screenshotNotRequestedCount": screenshotSkippedReasonsByWindowID.count,
            "realScreenshotCount": screenshotSourcesByWindowID.values.filter { source in
                if case .realScreenshot = source { return true }
                return false
            }.count,
            "skeletonFallbackCount": screenshotSourcesByWindowID.values.filter { source in
                if case .skeletonFallback = source { return true }
                return false
            }.count,
            "firstFrameLatencySampleCount": firstFrameLatencyMilliseconds.count,
            "firstFrameLatencyP95Milliseconds": jsonNumber(firstFrameP95),
            "firstFrameLatencyMaxMilliseconds": jsonNumber(firstFrameLatencyMilliseconds.max()),
            "keyboardResponseSampleCount": keyboardResponseLatencyMilliseconds.count,
            "keyboardResponseP95Milliseconds": jsonNumber(keyboardP95),
            "keyboardResponseMaxMilliseconds": jsonNumber(keyboardResponseLatencyMilliseconds.max()),
            "mouseResponseSampleCount": mouseResponseLatencyMilliseconds.count,
            "mouseResponseP95Milliseconds": jsonNumber(mouseP95),
            "mouseResponseMaxMilliseconds": jsonNumber(mouseResponseLatencyMilliseconds.max()),
            "hoverResponseSampleCount": hoverResponseLatencyMilliseconds.count,
            "hoverResponseP95Milliseconds": jsonNumber(hoverP95),
            "hoverResponseMaxMilliseconds": jsonNumber(hoverResponseLatencyMilliseconds.max()),
            "performanceThresholds": [
                "firstFrameMilliseconds": 150,
                "keyboardP95Milliseconds": 50,
                "hoverP95Milliseconds": 32
            ],
            "interactionPerformanceGatePassed": firstFrameGatePassed && keyboardGatePassed && hoverGatePassed
        ]
    }

    private static func shouldDismissOnEscape(_ event: NSEvent) -> Bool {
        let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
        return flags.isDisjoint(with: [.command, .option, .control])
    }

    private func performKeyboardCommand(_ rawCommand: String) {
        let command = rawCommand
            .trimmingCharacters(in: .whitespacesAndNewlines)
            .lowercased()
        guard !command.isEmpty else { return }

        switch command {
        case "left":
            recordKeyboardCommand("left")
            moveSelection(.left)
        case "right":
            recordKeyboardCommand("right")
            moveSelection(.right)
        case "up":
            recordKeyboardCommand("up")
            moveSelection(.up)
        case "down":
            recordKeyboardCommand("down")
            moveSelection(.down)
        case "enter", "return", "commit":
            recordKeyboardCommand("enter")
            commitCurrentSelection()
        case "tab":
            tabIgnoredCount += 1
            recordKeyboardCommand("tabIgnored")
        default:
            recordKeyboardCommand("unknown:\(command)")
        }
    }

    private func recordKeyboardCommand(_ command: String) {
        lastKeyboardCommand = command
        keyboardCommandsApplied.append(command)
    }

    private func performMouseCommand(_ rawCommand: String) {
        let command = rawCommand
            .trimmingCharacters(in: .whitespacesAndNewlines)
            .lowercased()
        guard !command.isEmpty else { return }

        let parts = command.split(separator: ":").map(String.init)
        switch parts.first {
        case "hover-app" where parts.count == 2:
            guard let appGroupIndex = Int(parts[1]) else {
                recordMouseCommand("invalid:\(command)")
                return
            }
            recordMouseCommand("hover-app:\(appGroupIndex)")
            hoverAppGroup(appGroupIndex)
        case "click-app" where parts.count == 2:
            guard let appGroupIndex = Int(parts[1]) else {
                recordMouseCommand("invalid:\(command)")
                return
            }
            recordMouseCommand("click-app:\(appGroupIndex)")
            clickAppShelfItem(appGroupIndex: appGroupIndex)
        case "scroll-app-shelf" where parts.count == 2:
            guard let targetOffset = Double(parts[1]) else {
                recordMouseCommand("invalid:\(command)")
                return
            }
            recordMouseCommand("scroll-app-shelf:\(parts[1])")
            scrollAppShelf(to: CGFloat(targetOffset))
        case "hover-space" where parts.count == 2:
            guard let spaceID = UInt64(parts[1]) else {
                recordMouseCommand("invalid:\(command)")
                return
            }
            recordMouseCommand("hover-space:\(spaceID)")
            if let segment = spaceLaneSegment(spaceID: spaceID) {
                hoverSpaceLaneSegment(segment)
            }
        case "click-space" where parts.count == 2:
            guard let spaceID = UInt64(parts[1]) else {
                recordMouseCommand("invalid:\(command)")
                return
            }
            recordMouseCommand("click-space:\(spaceID)")
            if let segment = spaceLaneSegment(spaceID: spaceID) {
                clickSpaceLaneSegment(segment)
            }
        case "hover-card" where parts.count == 3:
            guard let appGroupIndex = Int(parts[1]), let windowIndex = Int(parts[2]) else {
                recordMouseCommand("invalid:\(command)")
                return
            }
            recordMouseCommand("hover-card:\(appGroupIndex):\(windowIndex)")
            if let card = waterfallCard(appGroupIndex: appGroupIndex, windowIndex: windowIndex) {
                hoverWindowCard(card)
            }
        case "click-card" where parts.count == 3:
            guard let appGroupIndex = Int(parts[1]), let windowIndex = Int(parts[2]) else {
                recordMouseCommand("invalid:\(command)")
                return
            }
            recordMouseCommand("click-card:\(appGroupIndex):\(windowIndex)")
            if let card = waterfallCard(appGroupIndex: appGroupIndex, windowIndex: windowIndex) {
                clickWindowCard(card)
            }
        default:
            recordMouseCommand("unknown:\(command)")
        }
    }

    private func recordMouseCommand(_ command: String) {
        lastMouseCommand = command
        mouseCommandsApplied.append(command)
    }

    private func isHoverCommand(_ rawCommand: String) -> Bool {
        let command = rawCommand
            .trimmingCharacters(in: .whitespacesAndNewlines)
            .lowercased()
        return command.hasPrefix("hover-")
    }

    private func hoverAppGroup(_ appGroupIndex: Int) {
        hoveredSpaceLaneID = nil
        updateHoverState(
            appGroupIndex: appGroupIndex,
            windowID: nil,
            spaceID: nil,
            alignsWaterfallWithAppShelf: true
        )
    }

    private func hoverWindowCard(_ card: WaterfallCardLayers) {
        hoveredSpaceLaneID = nil
        updateHoverState(
            appGroupIndex: card.item.appGroupIndex,
            windowID: card.item.window.id,
            spaceID: card.item.primarySpaceID
        )
    }

    private func hoverSpaceLaneSegment(_ segment: SpaceLaneSegmentLayers) {
        focusSpace(segment.space.id, persistent: false)
    }

    private func clickSpaceLaneSegment(_ segment: SpaceLaneSegmentLayers) {
        DevelopmentDiagnostics.log("quickSwitch.view.clickSpaceLane", [
            "spaceID": segment.space.id,
            "label": segment.space.label
        ])
        focusSpace(segment.space.id, persistent: true)
    }

    private func focusSpace(_ spaceID: UInt64, persistent: Bool) {
        hoveredAppGroupIndex = nil
        hoveredWindowID = nil
        hoveredSpaceID = spaceID
        hoveredSpaceLaneID = spaceID
        if persistent {
            focusedSpaceID = spaceID
            lastSpaceLaneClickSpaceID = spaceID
        }

        let appGroupIndexes = spaceFocusedAppGroupIndexes(for: spaceID)
        lastSpaceFocusedAppGroupIndex = appGroupIndexes.first
        if let firstAppGroupIndex = appGroupIndexes.first {
            ensureAppShelfItemVisible(firstAppGroupIndex)
            ensureWaterfallColumnVisible(firstAppGroupIndex)
        }
        needsLayout = true
    }

    private func clickAppShelfItem(_ item: AppShelfItemLayers) {
        clickAppShelfItem(appGroupIndex: item.item.appGroupIndex)
    }

    private func clickAppShelfItem(appGroupIndex: Int) {
        guard let column = waterfallColumns.first(where: { $0.column.appGroupIndex == appGroupIndex }) else {
            DevelopmentDiagnostics.log("quickSwitch.view.clickAppShelf.missingColumn", [
                "appGroupIndex": appGroupIndex
            ])
            return
        }

        let previousSelection = effectiveSelection
        lastClickedAppGroupIndex = appGroupIndex
        DevelopmentDiagnostics.log("quickSwitch.view.clickAppShelf", [
            "appGroupIndex": appGroupIndex,
            "appName": column.column.app.name,
            "windowCount": column.cards.count
        ])
        if let firstCard = column.cards.first {
            let nextSelection = QuickSwitchSelection(
                appGroupIndex: firstCard.item.appGroupIndex,
                windowIndex: firstCard.item.windowIndex,
                windowID: firstCard.item.window.id
            )
            currentSelection = nextSelection
            columnSelectionHistory[nextSelection.appGroupIndex] = nextSelection.windowIndex
            lastAppShelfClickChangedSelection = previousSelection != nextSelection
            ensureWaterfallSelectionVisible(nextSelection, horizontalIntent: .alignWithAppShelf(animated: true))
        } else {
            lastAppShelfClickChangedSelection = false
            ensureWaterfallColumnVisible(column)
        }
        updateHoverState(appGroupIndex: appGroupIndex, windowID: nil, spaceID: nil)
        needsLayout = true
    }

    private func scrollAppShelf(to targetOffset: CGFloat) {
        layoutSubtreeIfNeeded()
        let previousOffset = appShelfScrollOffset
        appShelfScrollOffset = clampedAppShelfOffset(targetOffset)
        syncWaterfallToVisibleAppShelfItem(previousOffset: previousOffset)
        needsLayout = true
    }

    private func syncWaterfallToVisibleAppShelfItem(previousOffset: CGFloat) {
        guard appShelfMaxScrollOffset > 0 else { return }

        let visibleMinX = appShelfScrollOffset
        let visibleMaxX = appShelfScrollOffset + shelfLayer.bounds.width
        let visibleMidX = (visibleMinX + visibleMaxX) / 2
        let candidates = appShelfItems.filter { item in
            item.containerLayer.frame.maxX >= visibleMinX
                && item.containerLayer.frame.minX <= visibleMaxX
        }
        guard !candidates.isEmpty else { return }

        let movingRight = appShelfScrollOffset > previousOffset
        let best = candidates.sorted { lhs, rhs in
            let lhsDistance = abs(lhs.containerLayer.frame.midX - visibleMidX)
            let rhsDistance = abs(rhs.containerLayer.frame.midX - visibleMidX)
            if lhsDistance != rhsDistance {
                return lhsDistance < rhsDistance
            }
            return movingRight
                ? lhs.item.appGroupIndex > rhs.item.appGroupIndex
                : lhs.item.appGroupIndex < rhs.item.appGroupIndex
        }.first

        guard let best else { return }
        lastAppShelfScrollSyncedAppGroupIndex = best.item.appGroupIndex
        ensureWaterfallColumnVisible(best.item.appGroupIndex)
    }

    private func clickWindowCard(_ card: WaterfallCardLayers) {
        hoverWindowCard(card)
        let selection = QuickSwitchSelection(
            appGroupIndex: card.item.appGroupIndex,
            windowIndex: card.item.windowIndex,
            windowID: card.item.window.id
        )
        DevelopmentDiagnostics.log("quickSwitch.view.clickWindowCard", [
            "appGroupIndex": selection.appGroupIndex,
            "windowIndex": selection.windowIndex,
            "windowID": selection.windowID,
            "appName": card.item.window.app.name,
            "appPID": card.item.window.app.processIdentifier,
            "titleHash": DevelopmentDiagnostics.stableFingerprint(card.item.window.title),
            "titleLength": card.item.window.title.count,
            "titleIsEmpty": card.item.window.title.isEmpty,
            "isMinimized": card.item.window.isMinimized,
            "isFullscreen": card.item.window.isFullscreen,
            "identifierSource": String(describing: card.item.window.identifierSource)
        ])
        currentSelection = selection
        columnSelectionHistory[selection.appGroupIndex] = selection.windowIndex
        lastClickedWindowID = selection.windowID
        lastCommittedSelection = selection
        lastCommitSource = .mouse
        ensureCurrentSelectionVisible()
        onCommitSelection?(selection, .mouse)
    }

    private func updateHoverState(
        appGroupIndex: Int?,
        windowID: UInt32?,
        spaceID: UInt64?,
        alignsWaterfallWithAppShelf: Bool = false
    ) {
        guard hoveredAppGroupIndex != appGroupIndex
            || hoveredWindowID != windowID
            || hoveredSpaceID != spaceID
        else {
            if alignsWaterfallWithAppShelf, let appGroupIndex {
                alignWaterfallColumnWithAppShelfIcon(appGroupIndex: appGroupIndex, animated: true)
            }
            return
        }

        hoveredAppGroupIndex = appGroupIndex
        hoveredWindowID = windowID
        hoveredSpaceID = spaceID
        if alignsWaterfallWithAppShelf, let appGroupIndex {
            alignWaterfallColumnWithAppShelfIcon(appGroupIndex: appGroupIndex, animated: true)
        }
        needsLayout = true
    }

    private func moveSelection(_ direction: QuickSwitchKeyboardDirection) {
        guard let currentViewModel,
              let snapshot = snapshotForFocus(from: currentViewModel),
              let current = currentSelection ?? currentViewModel.initialSelection,
              let next = QuickSwitchFocusPolicy.nextSelection(
                from: current,
                in: snapshot,
                direction: direction,
                columnHistory: columnSelectionHistory
              )
        else {
            DevelopmentDiagnostics.log("quickSwitch.view.moveSelection.blocked", [
                "direction": String(describing: direction),
                "hasViewModel": currentViewModel != nil,
                "hasSelection": (currentSelection ?? currentViewModel?.initialSelection) != nil
            ])
            return
        }

        columnSelectionHistory[current.appGroupIndex] = current.windowIndex
        currentSelection = next
        columnSelectionHistory[next.appGroupIndex] = next.windowIndex
        ensureCurrentSelectionVisible(horizontalIntent: .alignWithAppShelf(animated: true))
        DevelopmentDiagnostics.log("quickSwitch.view.moveSelection", [
            "direction": String(describing: direction),
            "appGroupIndex": next.appGroupIndex,
            "windowIndex": next.windowIndex,
            "windowID": next.windowID
        ])
        needsLayout = true
    }

    private func commitCurrentSelection() {
        guard let selection = effectiveSelection else {
            DevelopmentDiagnostics.log("quickSwitch.view.commitCurrentSelection.blocked")
            return
        }

        currentSelection = selection
        columnSelectionHistory[selection.appGroupIndex] = selection.windowIndex
        lastCommittedSelection = selection
        lastCommitSource = .keyboard
        ensureCurrentSelectionVisible()
        DevelopmentDiagnostics.log("quickSwitch.view.commitCurrentSelection", [
            "appGroupIndex": selection.appGroupIndex,
            "windowIndex": selection.windowIndex,
            "windowID": selection.windowID
        ])
        onCommitSelection?(selection, .keyboard)
    }

    private var effectiveSelection: QuickSwitchSelection? {
        currentSelection ?? currentViewModel?.initialSelection
    }

    private func ensureCurrentSelectionVisible(horizontalIntent: WaterfallHorizontalIntent = .reveal) {
        guard let selection = effectiveSelection else { return }

        layoutSubtreeIfNeeded()
        ensureAppShelfSelectionVisible(selection)
        ensureWaterfallSelectionVisible(selection, horizontalIntent: horizontalIntent)
        needsLayout = true
        layoutSubtreeIfNeeded()
    }

    private func ensureAppShelfSelectionVisible(_ selection: QuickSwitchSelection) {
        ensureAppShelfItemVisible(selection.appGroupIndex)
    }

    private func ensureAppShelfItemVisible(_ appGroupIndex: Int) {
        guard let item = appShelfItems.first(where: { $0.item.appGroupIndex == appGroupIndex }) else {
            return
        }

        appShelfScrollOffset = clampedAppShelfOffset(
            scrollOffset(
                makingVisible: item.containerLayer.frame,
                currentOffset: appShelfScrollOffset,
                visibleWidth: shelfLayer.bounds.width,
                maxOffset: appShelfMaxScrollOffset,
                inset: WaterfallMetrics.revealPadding
            )
        )
    }

    private func ensureWaterfallSelectionVisible(
        _ selection: QuickSwitchSelection,
        horizontalIntent: WaterfallHorizontalIntent = .reveal
    ) {
        guard
            let column = waterfallColumns.first(where: { $0.column.appGroupIndex == selection.appGroupIndex })
        else {
            return
        }

        switch horizontalIntent {
        case .reveal:
            ensureWaterfallColumnVisible(column)
        case .alignWithAppShelf(let animated):
            alignWaterfallColumnWithAppShelfIcon(appGroupIndex: selection.appGroupIndex, animated: animated)
        }
        ensureWaterfallCardVisibleVertically(selection)
    }

    private func ensureWaterfallCardVisibleVertically(_ selection: QuickSwitchSelection) {
        let visibleHeight = max(
            1,
            waterfallLayer.bounds.height
                - WaterfallMetrics.headerHeight
                - WaterfallMetrics.columnPadding * 2
        )
        let cardStride = WaterfallMetrics.cardHeight + WaterfallMetrics.cardGap
        let cardStart = CGFloat(selection.windowIndex) * cardStride
        let cardEnd = cardStart + WaterfallMetrics.cardHeight
        let currentOffset = waterfallColumnScrollOffsets[selection.appGroupIndex] ?? 0
        let visibleStart = currentOffset
        let visibleEnd = currentOffset + visibleHeight
        var nextOffset = currentOffset

        if cardStart < visibleStart + WaterfallMetrics.revealPadding {
            nextOffset = cardStart - WaterfallMetrics.revealPadding
        } else if cardEnd > visibleEnd - WaterfallMetrics.revealPadding {
            nextOffset = cardEnd - visibleHeight + WaterfallMetrics.revealPadding
        }

        waterfallColumnScrollOffsets[selection.appGroupIndex] = clampedWaterfallColumnOffset(
            nextOffset,
            appGroupIndex: selection.appGroupIndex
        )
    }

    private func alignWaterfallColumnWithAppShelfIcon(appGroupIndex: Int, animated: Bool) {
        guard
            let item = appShelfItems.first(where: { $0.item.appGroupIndex == appGroupIndex }),
            let column = waterfallColumns.first(where: { $0.column.appGroupIndex == appGroupIndex })
        else {
            return
        }

        let targetOffset = targetWaterfallOffsetAligning(column: column, to: item)
        setWaterfallScrollOffset(targetOffset, animated: animated)
    }

    private func appShelfIconCenterXInWaterfallViewport(for item: AppShelfItemLayers) -> CGFloat {
        let iconCenterInShelfViewport = item.containerLayer.frame.minX
            + item.iconLayer.frame.midX
            - appShelfScrollOffset
        return shelfLayer.frame.minX + iconCenterInShelfViewport - waterfallLayer.frame.minX
    }

    private func targetWaterfallOffsetAligning(
        column: WaterfallColumnLayers,
        to item: AppShelfItemLayers
    ) -> CGFloat {
        column.containerLayer.frame.midX - appShelfIconCenterXInWaterfallViewport(for: item)
    }

    private func ensureWaterfallColumnVisible(_ appGroupIndex: Int) {
        guard let column = waterfallColumns.first(where: { $0.column.appGroupIndex == appGroupIndex }) else {
            return
        }

        ensureWaterfallColumnVisible(column)
    }

    private func ensureWaterfallColumnVisible(_ column: WaterfallColumnLayers) {
        waterfallScrollOffset = clampedWaterfallOffset(
            scrollOffset(
                makingVisible: column.containerLayer.frame,
                currentOffset: waterfallScrollOffset,
                visibleWidth: waterfallLayer.bounds.width,
                maxOffset: waterfallMaxScrollOffset,
                inset: WaterfallMetrics.revealPadding
            )
        )
    }

    private var waterfallAlignmentScrollRange: ClosedRange<CGFloat> {
        var minimumOffset: CGFloat = 0
        var maximumOffset = waterfallMaxScrollOffset

        for item in appShelfItems {
            guard let column = waterfallColumns.first(where: { $0.column.appGroupIndex == item.item.appGroupIndex }) else {
                continue
            }

            let targetOffset = targetWaterfallOffsetAligning(column: column, to: item)
            minimumOffset = min(minimumOffset, targetOffset)
            maximumOffset = max(maximumOffset, targetOffset)
        }

        return minimumOffset...max(minimumOffset, maximumOffset)
    }

    private var waterfallAlignmentScrollable: Bool {
        let range = waterfallAlignmentScrollRange
        return range.upperBound - range.lowerBound > 0.5
    }

    private func clampedWaterfallAlignmentOffset(_ offset: CGFloat) -> CGFloat {
        let range = waterfallAlignmentScrollRange
        return min(max(range.lowerBound, offset), range.upperBound)
    }

    private func setWaterfallScrollOffset(_ offset: CGFloat, animated: Bool) {
        let nextOffset = clampedWaterfallAlignmentOffset(offset)
        let previousPositionX = waterfallContentLayer.presentation()?.position.x
            ?? waterfallContentLayer.position.x

        waterfallScrollOffset = nextOffset
        CATransaction.begin()
        CATransaction.setDisableActions(true)
        waterfallContentLayer.frame = CGRect(
            x: -waterfallScrollOffset,
            y: 0,
            width: waterfallContentWidth,
            height: waterfallLayer.bounds.height
        )
        CATransaction.commit()

        let nextPositionX = waterfallContentLayer.position.x
        guard animated,
              !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion,
              abs(previousPositionX - nextPositionX) > 0.5
        else {
            waterfallContentLayer.removeAnimation(forKey: "waterfallColumnAlignment")
            return
        }

        let animation = CABasicAnimation(keyPath: "position.x")
        animation.fromValue = previousPositionX
        animation.toValue = nextPositionX
        animation.duration = WaterfallAlignmentMetrics.animationDuration
        animation.timingFunction = CAMediaTimingFunction(name: WaterfallAlignmentMetrics.animationTimingName)
        animation.isRemovedOnCompletion = true
        waterfallContentLayer.add(animation, forKey: "waterfallColumnAlignment")
    }

    private func scrollOffset(
        makingVisible frame: CGRect,
        currentOffset: CGFloat,
        visibleWidth: CGFloat,
        maxOffset: CGFloat,
        inset: CGFloat
    ) -> CGFloat {
        guard visibleWidth > 0, maxOffset > 0 else { return currentOffset }

        let visibleMinX = currentOffset
        let visibleMaxX = currentOffset + visibleWidth
        var nextOffset = currentOffset

        if frame.minX < visibleMinX + inset {
            nextOffset = frame.minX - inset
        } else if frame.maxX > visibleMaxX - inset {
            nextOffset = frame.maxX - visibleWidth + inset
        }

        return min(max(0, nextOffset), maxOffset)
    }

    private func snapshotForFocus(from viewModel: QuickSwitchViewModel) -> QuickSwitchSnapshot? {
        let appGroups = viewModel.waterfallColumns.map { column in
            QuickSwitchAppGroup(
                app: column.app,
                windows: column.windows.map { card in
                    QuickSwitchWindowItem(
                        window: card.window,
                        primarySpaceID: card.primarySpaceID
                    )
                }
            )
        }
        guard !appGroups.isEmpty else { return nil }

        let displays = viewModel.displays.map { display in
            AlignerDisplay(
                uuid: display.displayUUID,
                physical: display.physical,
                spaces: display.spaces.map { space in
                    AlignerSpace(
                        id: space.id,
                        type: space.type,
                        displayUUID: space.displayUUID,
                        index: space.index
                    )
                }
            )
        }

        return QuickSwitchSnapshot(displays: displays, appGroups: appGroups)
    }

    private func milliseconds(since start: CFTimeInterval) -> Double {
        (CACurrentMediaTime() - start) * 1_000
    }

    private func percentile95(_ values: [Double]) -> Double? {
        guard !values.isEmpty else { return nil }

        let sortedValues = values.sorted()
        let index = min(
            sortedValues.count - 1,
            Int(ceil(Double(sortedValues.count) * 0.95)) - 1
        )
        return sortedValues[index]
    }

    private func jsonNumber(_ value: Double?) -> Any {
        value ?? NSNull()
    }

    private func setupBackdropBlurView() {
        backdropBlurView.material = .fullScreenUI
        backdropBlurView.blendingMode = .behindWindow
        backdropBlurView.state = .active
        backdropBlurView.isEmphasized = false
        backdropBlurView.frame = bounds
        backdropBlurView.autoresizingMask = [.width, .height]
        addSubview(backdropBlurView, positioned: .below, relativeTo: nil)
    }

    private func setupLayerHostView() {
        layerHostView.wantsLayer = true
        layerHostView.frame = bounds
        layerHostView.autoresizingMask = [.width, .height]
        layerHostView.layer?.masksToBounds = true
        layerHostView.layer?.backgroundColor = NSColor.clear.cgColor
        addSubview(layerHostView, positioned: .above, relativeTo: backdropBlurView)
    }

    private func setupLayers() {
        guard let rootLayer = layerHostView.layer else { return }

        rootLayer.masksToBounds = true
        backgroundLayer.colors = [
            NSColor.windowBackgroundColor.withAlphaComponent(0.58).cgColor,
            NSColor.controlBackgroundColor.withAlphaComponent(0.48).cgColor
        ]
        backgroundLayer.startPoint = CGPoint(x: 0.5, y: 1.0)
        backgroundLayer.endPoint = CGPoint(x: 0.5, y: 0.0)
        rootLayer.addSublayer(backgroundLayer)

        safeAreaFillLayer.backgroundColor = NSColor.black.cgColor
        rootLayer.addSublayer(safeAreaFillLayer)

        glassLayer.cornerRadius = 0
        glassLayer.backgroundColor = NSColor.clear.cgColor
        glassLayer.borderColor = NSColor.clear.cgColor
        glassLayer.borderWidth = 0
        glassLayer.shadowOpacity = 0
        rootLayer.addSublayer(glassLayer)

        laneLayer.backgroundColor = NSColor.controlBackgroundColor.withAlphaComponent(0.68).cgColor
        laneLayer.cornerRadius = 16
        laneLayer.masksToBounds = true
        glassLayer.addSublayer(laneLayer)
        laneLayer.addSublayer(spaceLaneContentLayer)

        shelfLayer.backgroundColor = NSColor.controlBackgroundColor.withAlphaComponent(0.60).cgColor
        shelfLayer.cornerRadius = 16
        shelfLayer.masksToBounds = true
        glassLayer.addSublayer(shelfLayer)
        shelfLayer.addSublayer(appShelfContentLayer)

        waterfallLayer.backgroundColor = NSColor.clear.cgColor
        waterfallLayer.masksToBounds = true
        glassLayer.addSublayer(waterfallLayer)
        waterfallLayer.addSublayer(waterfallContentLayer)
    }

    private func rebuildAppShelfItems() {
        for item in appShelfItems {
            item.containerLayer.removeFromSuperlayer()
        }

        let selectedAppGroupIndex = effectiveSelection?.appGroupIndex
        appShelfItems = (currentViewModel?.appShelf ?? []).map { item in
            let container = CALayer()
            container.name = item.app.name

            let background = CALayer()
            background.cornerRadius = 10
            background.backgroundColor = (item.appGroupIndex == selectedAppGroupIndex
                ? NSColor.systemFill.withAlphaComponent(0.16)
                : NSColor.clear
            ).cgColor
            background.borderColor = (item.appGroupIndex == selectedAppGroupIndex
                ? NSColor.separatorColor.withAlphaComponent(0.36)
                : NSColor.clear
            ).cgColor
            background.borderWidth = item.appGroupIndex == selectedAppGroupIndex ? 1 : 0

            let icon = CALayer()
            icon.contentsGravity = .resizeAspect
            icon.contentsScale = backingScaleFactor
            icon.contents = appIconProvider.icon(for: item.app)
            icon.cornerRadius = 12
            icon.masksToBounds = false

            let label = makeTextLayer(
                string: item.app.name,
                fontSize: 11,
                weight: .regular,
                color: .secondaryLabelColor,
                alignment: .center
            )

            let badge = makeTextLayer(
                string: item.windowCount > 1 ? "\(item.windowCount)" : "",
                fontSize: 10,
                weight: .semibold,
                color: .white,
                alignment: .center
            )
            badge.backgroundColor = NSColor.controlAccentColor.withAlphaComponent(0.90).cgColor
            badge.cornerRadius = 8
            badge.masksToBounds = true

            let selectedIndicator = CALayer()
            selectedIndicator.isHidden = true

            container.addSublayer(background)
            container.addSublayer(icon)
            container.addSublayer(label)
            container.addSublayer(badge)
            appShelfContentLayer.addSublayer(container)

            return AppShelfItemLayers(
                item: item,
                containerLayer: container,
                backgroundLayer: background,
                iconLayer: icon,
                labelLayer: label,
                badgeLayer: badge,
                selectedIndicatorLayer: selectedIndicator
            )
        }
    }

    private func rebuildWaterfallColumns() {
        for column in waterfallColumns {
            column.containerLayer.removeFromSuperlayer()
        }

        let existingOffsets = waterfallColumnScrollOffsets
        waterfallColumns = (currentViewModel?.waterfallColumns ?? []).map { column in
            let container = CALayer()
            container.name = column.app.name
            container.cornerRadius = 14
            container.masksToBounds = true
            container.backgroundColor = NSColor.controlBackgroundColor.withAlphaComponent(0.56).cgColor
            container.borderColor = NSColor.separatorColor.withAlphaComponent(0.34).cgColor
            container.borderWidth = 1

            let header = CALayer()
            header.backgroundColor = NSColor.controlBackgroundColor.withAlphaComponent(0.68).cgColor

            let appName = makeTextLayer(
                string: column.app.name,
                fontSize: 13,
                weight: .semibold,
                color: .labelColor
            )
            let count = makeTextLayer(
                string: "\(column.windows.count)",
                fontSize: 11,
                weight: .medium,
                color: .secondaryLabelColor,
                alignment: .right
            )

            container.addSublayer(header)
            container.addSublayer(appName)
            container.addSublayer(count)

            let cards = column.windows.map { window in
                let card = CALayer()
                card.cornerRadius = 12
                card.masksToBounds = false

                let thumbnail = CALayer()
                thumbnail.cornerRadius = 8
                thumbnail.contentsGravity = .resizeAspectFill
                thumbnail.contentsScale = backingScaleFactor
                thumbnail.masksToBounds = true
                thumbnail.contents = skeletonThumbnailProvider
                    .withOverlayTitle(window.window.title, for: window.window.app)

                let title = makeTextLayer(
                    string: window.window.title.isEmpty ? "Untitled Window" : window.window.title,
                    fontSize: 12,
                    weight: .medium,
                    color: .labelColor
                )
                title.truncationMode = .middle
                let meta = makeTextLayer(
                    string: waterfallMetaText(for: window),
                    fontSize: 10,
                    weight: .regular,
                    color: .secondaryLabelColor
                )
                let appIcon = CALayer()
                appIcon.contentsGravity = .resizeAspect
                appIcon.contentsScale = backingScaleFactor
                appIcon.contents = appIconProvider.icon(for: window.window.app)
                appIcon.cornerRadius = 5
                appIcon.masksToBounds = true

                let state = makeTextLayer(
                    string: waterfallStateText(for: window),
                    fontSize: 10,
                    weight: .medium,
                    color: .secondaryLabelColor,
                    alignment: .right
                )
                let shine = CAGradientLayer()
                shine.colors = [
                    NSColor.white.withAlphaComponent(0.00).cgColor,
                    NSColor.white.withAlphaComponent(0.16).cgColor,
                    NSColor.white.withAlphaComponent(0.00).cgColor
                ]
                shine.startPoint = CGPoint(x: 0, y: 1)
                shine.endPoint = CGPoint(x: 1, y: 0)
                shine.opacity = 0

                card.addSublayer(thumbnail)
                card.addSublayer(appIcon)
                card.addSublayer(title)
                card.addSublayer(meta)
                card.addSublayer(state)
                card.addSublayer(shine)
                container.addSublayer(card)

                return WaterfallCardLayers(
                    item: window,
                    containerLayer: card,
                    titleLayer: title,
                    metaLayer: meta,
                    thumbnailLayer: thumbnail,
                    appIconLayer: appIcon,
                    stateLayer: state,
                    shineLayer: shine
                )
            }

            waterfallContentLayer.addSublayer(container)

            return WaterfallColumnLayers(
                column: column,
                containerLayer: container,
                headerLayer: header,
                appNameLayer: appName,
                countLayer: count,
                cards: cards
            )
        }

        let validAppGroupIndexes = Set(waterfallColumns.map(\.column.appGroupIndex))
        waterfallColumnScrollOffsets = existingOffsets.filter { validAppGroupIndexes.contains($0.key) }
    }

    private func rebuildSpaceLaneSegments() {
        for segment in spaceLaneSegments {
            segment.containerLayer.removeFromSuperlayer()
        }

        let spaces = currentViewModel?.displays.flatMap(\.spaces) ?? []
        spaceLaneSegments = spaces.map { space in
            let container = CALayer()
            container.name = space.label
            container.cornerRadius = 10
            container.borderWidth = 1
            container.borderColor = NSColor.separatorColor.withAlphaComponent(0.34).cgColor
            container.backgroundColor = spaceColor(for: space).cgColor
            container.shadowColor = NSColor.black.cgColor

            let labelLayer = makeTextLayer(
                string: space.label,
                fontSize: 15,
                weight: .semibold,
                color: .labelColor
            )
            let countLayer = makeTextLayer(
                string: "\(space.windowCount)",
                fontSize: 12,
                weight: .medium,
                color: .secondaryLabelColor,
                alignment: .center
            )
            let appLayer = makeTextLayer(
                string: appIdentifierText(for: space.appNames),
                fontSize: 12,
                weight: .regular,
                color: .secondaryLabelColor
            )
            let windowBlocks = makeWindowBlocks(count: min(space.windowCount, 5), space: space)
            let fullscreenMarkerLayer = makeFullscreenMarkerLayer(for: space)

            container.addSublayer(labelLayer)
            container.addSublayer(countLayer)
            container.addSublayer(appLayer)
            if let fullscreenMarkerLayer {
                container.addSublayer(fullscreenMarkerLayer)
            }
            for block in windowBlocks {
                container.addSublayer(block)
            }
            spaceLaneContentLayer.addSublayer(container)

            return SpaceLaneSegmentLayers(
                space: space,
                containerLayer: container,
                labelLayer: labelLayer,
                countLayer: countLayer,
                appLayer: appLayer,
                windowBlocks: windowBlocks,
                fullscreenMarkerLayer: fullscreenMarkerLayer
            )
        }
    }

    private func layoutLayers() {
        CATransaction.begin()
        CATransaction.setDisableActions(true)

        backgroundLayer.frame = bounds

        let safeAreaTopInset = topSafeAreaInset
        safeAreaFillLayer.frame = CGRect(
            x: 0,
            y: max(0, bounds.height - safeAreaTopInset),
            width: bounds.width,
            height: safeAreaTopInset
        )
        safeAreaFillLayer.isHidden = safeAreaTopInset <= 0.5
        glassLayer.frame = bounds

        let contentBounds = glassLayer.bounds
        let horizontalMargin = RootLayoutMetrics.horizontalMargin
        let topMargin = safeAreaTopInset + RootLayoutMetrics.topContentMargin
        let laneHeight = min(104, max(82, contentBounds.height * 0.12))
        let availableContentWidth = contentBounds.width - horizontalMargin * 2
        appShelfLayout = appShelfLayout(for: availableContentWidth)
        let shelfHeight = appShelfHeight(forRows: appShelfLayout.rows)
        laneLayer.frame = CGRect(
            x: horizontalMargin,
            y: contentBounds.height - topMargin - laneHeight,
            width: availableContentWidth,
            height: laneHeight
        )
        shelfLayer.frame = CGRect(
            x: horizontalMargin,
            y: laneLayer.frame.minY - RootLayoutMetrics.shelfGap - shelfHeight,
            width: laneLayer.frame.width,
            height: shelfHeight
        )
        waterfallLayer.frame = CGRect(
            x: shelfLayer.frame.minX,
            y: RootLayoutMetrics.bottomMargin,
            width: shelfLayer.frame.width,
            height: max(1, shelfLayer.frame.minY - RootLayoutMetrics.bottomMargin - RootLayoutMetrics.waterfallTopGap)
        )

        layoutSpaceLaneSegments()
        layoutAppShelfItems()
        layoutWaterfallColumns()

        CATransaction.commit()
    }

    private var topSafeAreaInset: CGFloat {
        max(0, window?.screen?.safeAreaInsets.top ?? safeAreaInsets.top)
    }

    private func appShelfLayout(for availableWidth: CGFloat) -> AppShelfLayout {
        let itemCount = appShelfItems.count
        guard itemCount > 0 else {
            return AppShelfLayout(rows: 0, iconSize: AppShelfMetrics.normalIconSize)
        }

        let innerWidth = max(1, availableWidth - 24)
        let normalOneRowWidth = widthForAppShelfItems(
            count: itemCount,
            itemWidth: appShelfSlotWidth(forIconSize: AppShelfMetrics.normalIconSize),
            gap: AppShelfMetrics.normalGap
        )
        if normalOneRowWidth <= innerWidth {
            return AppShelfLayout(rows: 1, iconSize: AppShelfMetrics.normalIconSize)
        }

        if let compressedOneRowIconSize = compressedAppShelfIconSize(
            fitting: itemCount,
            availableWidth: innerWidth
        ) {
            return AppShelfLayout(
                rows: 1,
                iconSize: compressedOneRowIconSize
            )
        }

        let maxItemsPerRow = Int(ceil(Double(itemCount) / Double(AppShelfMetrics.maxRows)))
        let twoRowIconSize = compressedAppShelfIconSize(
            fitting: maxItemsPerRow,
            availableWidth: innerWidth
        ) ?? AppShelfMetrics.minIconSize
        return AppShelfLayout(
            rows: AppShelfMetrics.maxRows,
            iconSize: twoRowIconSize
        )
    }

    private func compressedAppShelfIconSize(fitting itemCount: Int, availableWidth: CGFloat) -> CGFloat? {
        let minimumWidth = widthForAppShelfItems(
            count: itemCount,
            itemWidth: appShelfSlotWidth(forIconSize: AppShelfMetrics.minIconSize),
            gap: AppShelfMetrics.minGap
        )
        guard minimumWidth <= availableWidth else { return nil }

        let rawIconSize = floor(
            (availableWidth - CGFloat(itemCount - 1) * AppShelfMetrics.minGap) / CGFloat(itemCount)
                - appShelfSlotPadding
        )
        return max(AppShelfMetrics.minIconSize, min(AppShelfMetrics.normalIconSize, rawIconSize))
    }

    private func appShelfHeight(forRows rows: Int) -> CGFloat {
        switch rows {
        case 0, 1:
            return 92
        default:
            return 148
        }
    }

    private var appShelfSlotPadding: CGFloat {
        20
    }

    private func appShelfSlotWidth(forIconSize iconSize: CGFloat) -> CGFloat {
        max(iconSize + appShelfSlotPadding, 64)
    }

    private func widthForAppShelfItems(count: Int, itemWidth: CGFloat, gap: CGFloat) -> CGFloat {
        guard count > 0 else { return 0 }
        return CGFloat(count) * itemWidth + CGFloat(count - 1) * gap
    }

    private func layoutSpaceLaneSegments() {
        guard !spaceLaneSegments.isEmpty else { return }

        let gap: CGFloat = 10
        let segmentHeight = max(1, laneLayer.bounds.height - 20)
        let availableWidth = laneLayer.bounds.width - 24 - CGFloat(spaceLaneSegments.count - 1) * gap
        let segmentWidth = max(96, min(150, availableWidth / CGFloat(spaceLaneSegments.count)))
        spaceLaneContentWidth = max(
            laneLayer.bounds.width,
            24 + CGFloat(spaceLaneSegments.count) * segmentWidth + CGFloat(spaceLaneSegments.count - 1) * gap
        )
        spaceLaneScrollOffset = clampedSpaceLaneOffset(spaceLaneScrollOffset)
        spaceLaneContentLayer.frame = CGRect(
            x: -spaceLaneScrollOffset,
            y: 0,
            width: spaceLaneContentWidth,
            height: laneLayer.bounds.height
        )

        var x: CGFloat = 12

        for segment in spaceLaneSegments {
            segment.containerLayer.frame = CGRect(x: x, y: 10, width: segmentWidth, height: segmentHeight)
            applySpaceLaneVisualState(segment)
            layoutSpaceLaneSegmentContents(segment)
            x += segmentWidth + gap
        }
    }

    private var spaceLaneMaxScrollOffset: CGFloat {
        max(0, spaceLaneContentWidth - laneLayer.bounds.width)
    }

    private func clampedSpaceLaneOffset(_ offset: CGFloat) -> CGFloat {
        min(max(0, offset), spaceLaneMaxScrollOffset)
    }

    private func applySpaceLaneVisualState(_ segment: SpaceLaneSegmentLayers) {
        let isHovered = segment.space.id == hoveredSpaceID
        let isFocused = segment.space.id == activeSpaceFocusID
        let isCurrent = segment.space.isCurrent
        let isActive = isHovered || isFocused

        segment.containerLayer.borderWidth = isCurrent ? 1.5 : 1
        segment.containerLayer.borderColor = (isCurrent
            ? NSColor.labelColor.withAlphaComponent(0.34)
            : isActive
                ? NSColor.labelColor.withAlphaComponent(0.24)
                : NSColor.separatorColor.withAlphaComponent(0.34)
        ).cgColor
        segment.containerLayer.backgroundColor = (isActive
            ? NSColor.windowBackgroundColor.withAlphaComponent(0.76)
            : spaceColor(for: segment.space)
        ).cgColor
        segment.containerLayer.shadowOpacity = isCurrent ? 0.12 : isActive ? 0.08 : 0
        segment.containerLayer.shadowRadius = isCurrent ? 10 : isActive ? 7 : 0
        segment.containerLayer.shadowOffset = CGSize(width: 0, height: isCurrent ? -2 : -1)
        segment.containerLayer.shadowPath = CGPath(
            roundedRect: segment.containerLayer.bounds,
            cornerWidth: segment.containerLayer.cornerRadius,
            cornerHeight: segment.containerLayer.cornerRadius,
            transform: nil
        )
    }

    private func shouldScrollSpaceLane(for event: NSEvent) -> Bool {
        guard let window else { return false }

        let locationInView = convert(event.locationInWindow, from: nil)
        let laneFrameInView = laneLayer.frame.offsetBy(dx: glassLayer.frame.minX, dy: glassLayer.frame.minY)
        return window == self.window && laneFrameInView.contains(locationInView)
    }

    private func shouldScrollAppShelf(for event: NSEvent) -> Bool {
        guard let window else { return false }

        let locationInView = convert(event.locationInWindow, from: nil)
        let shelfFrameInView = shelfLayer.frame.offsetBy(dx: glassLayer.frame.minX, dy: glassLayer.frame.minY)
        return window == self.window && shelfFrameInView.contains(locationInView)
    }

    private func shouldScrollWaterfall(for event: NSEvent) -> Bool {
        guard let window else { return false }

        let locationInView = convert(event.locationInWindow, from: nil)
        let waterfallFrameInView = waterfallLayer.frame.offsetBy(dx: glassLayer.frame.minX, dy: glassLayer.frame.minY)
        return window == self.window && waterfallFrameInView.contains(locationInView)
    }

    private func waterfallColumn(at windowLocation: CGPoint) -> WaterfallColumnLayers? {
        let locationInView = convert(windowLocation, from: nil)
        let locationInWaterfallContent = CGPoint(
            x: locationInView.x - glassLayer.frame.minX - waterfallLayer.frame.minX - waterfallContentLayer.frame.minX,
            y: locationInView.y - glassLayer.frame.minY - waterfallLayer.frame.minY - waterfallContentLayer.frame.minY
        )

        return waterfallColumns.first { column in
            column.containerLayer.frame.contains(locationInWaterfallContent)
        }
    }

    private func spaceLaneSegment(at windowLocation: CGPoint) -> SpaceLaneSegmentLayers? {
        let locationInView = convert(windowLocation, from: nil)
        let locationInSpaceLaneContent = CGPoint(
            x: locationInView.x - glassLayer.frame.minX - laneLayer.frame.minX - spaceLaneContentLayer.frame.minX,
            y: locationInView.y - glassLayer.frame.minY - laneLayer.frame.minY - spaceLaneContentLayer.frame.minY
        )

        return spaceLaneSegments.first { segment in
            segment.containerLayer.frame.contains(locationInSpaceLaneContent)
        }
    }

    private func spaceLaneSegment(spaceID: UInt64) -> SpaceLaneSegmentLayers? {
        spaceLaneSegments.first { $0.space.id == spaceID }
    }

    private func appShelfItem(at windowLocation: CGPoint) -> AppShelfItemLayers? {
        let locationInView = convert(windowLocation, from: nil)
        let locationInShelfContent = CGPoint(
            x: locationInView.x - glassLayer.frame.minX - shelfLayer.frame.minX - appShelfContentLayer.frame.minX,
            y: locationInView.y - glassLayer.frame.minY - shelfLayer.frame.minY - appShelfContentLayer.frame.minY
        )

        return appShelfItems.first { item in
            item.containerLayer.frame.contains(locationInShelfContent)
        }
    }

    private func waterfallCard(at windowLocation: CGPoint) -> WaterfallCardLayers? {
        let locationInView = convert(windowLocation, from: nil)
        let locationInWaterfallContent = CGPoint(
            x: locationInView.x - glassLayer.frame.minX - waterfallLayer.frame.minX - waterfallContentLayer.frame.minX,
            y: locationInView.y - glassLayer.frame.minY - waterfallLayer.frame.minY - waterfallContentLayer.frame.minY
        )

        for column in waterfallColumns where column.containerLayer.frame.contains(locationInWaterfallContent) {
            let locationInColumn = CGPoint(
                x: locationInWaterfallContent.x - column.containerLayer.frame.minX,
                y: locationInWaterfallContent.y - column.containerLayer.frame.minY
            )
            if let card = column.cards.first(where: { $0.containerLayer.frame.contains(locationInColumn) }) {
                return card
            }
        }

        return nil
    }

    private func waterfallCard(appGroupIndex: Int, windowIndex: Int) -> WaterfallCardLayers? {
        waterfallColumns
            .first(where: { $0.column.appGroupIndex == appGroupIndex })?
            .cards
            .first(where: { $0.item.windowIndex == windowIndex })
    }

    private func layoutSpaceLaneSegmentContents(_ segment: SpaceLaneSegmentLayers) {
        let bounds = segment.containerLayer.bounds
        segment.labelLayer.frame = CGRect(x: 10, y: bounds.height - 29, width: max(1, bounds.width - 48), height: 20)
        segment.countLayer.frame = CGRect(x: bounds.width - 34, y: bounds.height - 29, width: 24, height: 20)
        segment.appLayer.frame = CGRect(x: 10, y: 9, width: max(1, bounds.width - 20), height: 17)
        segment.fullscreenMarkerLayer?.frame = CGRect(x: 10, y: bounds.height - 7, width: max(1, bounds.width - 20), height: 3)

        let blockGap: CGFloat = 5
        let blockWidth = max(12, min(22, (bounds.width - 20 - CGFloat(max(0, segment.windowBlocks.count - 1)) * blockGap) / CGFloat(max(1, segment.windowBlocks.count))))
        let blockHeight: CGFloat = 14
        var x: CGFloat = 10

        for block in segment.windowBlocks {
            block.frame = CGRect(x: x, y: 31, width: blockWidth, height: blockHeight)
            x += blockWidth + blockGap
        }
    }

    private func layoutAppShelfItems() {
        guard !appShelfItems.isEmpty else {
            appShelfContentWidth = shelfLayer.bounds.width
            appShelfScrollOffset = 0
            appShelfContentLayer.frame = shelfLayer.bounds
            return
        }

        let rows = appShelfRows()
        let iconSize = appShelfLayout.iconSize
        let gap = appShelfGap(forIconSize: iconSize)
        let itemWidth = appShelfSlotWidth(forIconSize: iconSize)
        let rowHeight: CGFloat = AppShelfMetrics.selectedIconSize + 18
        let rowGap: CGFloat = appShelfLayout.rows > 1 ? 8 : 0
        let innerWidth = max(1, shelfLayer.bounds.width - 24)
        let maxRowWidth = rows
            .map { widthForAppShelfItems(count: $0.count, itemWidth: itemWidth, gap: gap) }
            .max() ?? innerWidth
        appShelfContentWidth = max(shelfLayer.bounds.width, maxRowWidth + 24)
        appShelfScrollOffset = clampedAppShelfOffset(appShelfScrollOffset)
        appShelfContentLayer.frame = CGRect(
            x: -appShelfScrollOffset,
            y: 0,
            width: appShelfContentWidth,
            height: shelfLayer.bounds.height
        )

        let totalRowsHeight = CGFloat(rows.count) * rowHeight + CGFloat(max(0, rows.count - 1)) * rowGap
        var y = shelfLayer.bounds.midY + totalRowsHeight / 2 - rowHeight

        for row in rows {
            let rowWidth = widthForAppShelfItems(count: row.count, itemWidth: itemWidth, gap: gap)
            var x = max(12, (appShelfContentWidth - rowWidth) / 2)

            for item in row {
                item.containerLayer.frame = CGRect(x: x, y: y, width: itemWidth, height: rowHeight)
                layoutAppShelfItemContents(item, iconSize: iconSize)
                x += itemWidth + gap
            }

            y -= rowHeight + rowGap
        }
    }

    private func layoutAppShelfItemContents(_ item: AppShelfItemLayers, iconSize: CGFloat) {
        let bounds = item.containerLayer.bounds
        let isSelected = item.item.appGroupIndex == effectiveSelection?.appGroupIndex
        let isHovered = item.item.appGroupIndex == effectiveHoveredAppGroupIndex
        let isSpaceFocused = spaceFocusWindowCount(for: item.item.appGroupIndex) > 0
        let visualIconSize = appShelfVisualIconSize(forBaseIconSize: iconSize, selected: isSelected, hovered: isHovered)
        let backgroundPadding: CGFloat = (isSelected || isHovered) ? 4 : 2
        let iconX = (bounds.width - visualIconSize) / 2
        let iconY = bounds.height - visualIconSize - 2
        let badgeText = appShelfBadgeText(for: item)
        let badgeWidth = max(18, CGFloat(badgeText.count) * 7 + 8)

        item.containerLayer.zPosition = appShelfZPosition(selected: isSelected, hovered: isHovered)
        item.backgroundLayer.backgroundColor = appShelfBackgroundColor(
            selected: isSelected,
            hovered: isHovered,
            spaceFocused: isSpaceFocused
        ).cgColor
        item.backgroundLayer.borderColor = (isSelected
            ? NSColor.separatorColor.withAlphaComponent(0.38)
            : isHovered
                ? NSColor.separatorColor.withAlphaComponent(0.28)
                : NSColor.clear
        ).cgColor
        item.backgroundLayer.borderWidth = (isSelected || isHovered) ? 1 : 0
        item.backgroundLayer.shadowColor = NSColor.black.cgColor
        item.backgroundLayer.shadowOpacity = isSelected ? 0.11 : isHovered ? 0.06 : 0
        item.backgroundLayer.shadowRadius = isSelected ? 10 : isHovered ? 7 : 0
        item.backgroundLayer.shadowOffset = CGSize(width: 0, height: -2)
        item.backgroundLayer.frame = CGRect(
            x: iconX - backgroundPadding,
            y: iconY - backgroundPadding,
            width: visualIconSize + backgroundPadding * 2,
            height: visualIconSize + backgroundPadding * 2
        )
        item.iconLayer.frame = CGRect(x: iconX, y: iconY, width: visualIconSize, height: visualIconSize)
        item.labelLayer.contentsScale = backingScaleFactor
        item.labelLayer.frame = CGRect(x: 0, y: 0, width: bounds.width, height: 14)
        item.badgeLayer.string = badgeText
        item.badgeLayer.isHidden = badgeText.isEmpty
        item.badgeLayer.backgroundColor = (isSpaceFocused
            ? NSColor.controlAccentColor.withAlphaComponent(0.88)
            : NSColor.controlAccentColor.withAlphaComponent(0.90)
        ).cgColor
        item.badgeLayer.frame = CGRect(
            x: iconX - 3,
            y: iconY - 2,
            width: badgeWidth,
            height: 16
        )
        item.selectedIndicatorLayer.frame = .zero
        item.selectedIndicatorLayer.backgroundColor = NSColor.clear.cgColor
    }

    private func appShelfRows() -> [[AppShelfItemLayers]] {
        guard appShelfLayout.rows > 1 else { return [appShelfItems] }

        let firstRowCount = Int(ceil(Double(appShelfItems.count) / Double(AppShelfMetrics.maxRows)))
        return [
            Array(appShelfItems.prefix(firstRowCount)),
            Array(appShelfItems.dropFirst(firstRowCount))
        ].filter { !$0.isEmpty }
    }

    private func appShelfGap(forIconSize iconSize: CGFloat) -> CGFloat {
        if iconSize >= AppShelfMetrics.normalIconSize {
            return AppShelfMetrics.normalGap
        }

        return AppShelfMetrics.minGap
    }

    private var effectiveHoveredAppGroupIndex: Int? {
        debugHoveredAppGroupIndex ?? hoveredAppGroupIndex
    }

    private var activeSpaceFocusID: UInt64? {
        focusedSpaceID ?? hoveredSpaceLaneID
    }

    private func spaceFocusedAppGroupIndexes() -> [Int] {
        spaceFocusedAppGroupIndexes(for: activeSpaceFocusID)
    }

    private func spaceFocusedAppGroupIndexes(for spaceID: UInt64?) -> [Int] {
        guard let spaceID else { return [] }

        return waterfallColumns
            .filter { column in
                column.cards.contains { $0.item.primarySpaceID == spaceID }
            }
            .map(\.column.appGroupIndex)
            .sorted()
    }

    private func spaceFocusWindowCount(for appGroupIndex: Int) -> Int {
        guard let activeSpaceFocusID else { return 0 }

        return waterfallColumns
            .first(where: { $0.column.appGroupIndex == appGroupIndex })?
            .cards
            .filter { $0.item.primarySpaceID == activeSpaceFocusID }
            .count ?? 0
    }

    private func spaceFocusDirection(for appGroupIndex: Int) -> String {
        guard spaceFocusWindowCount(for: appGroupIndex) > 0,
              let column = waterfallColumns.first(where: { $0.column.appGroupIndex == appGroupIndex })
        else {
            return "none"
        }

        let visibleMinX = waterfallScrollOffset
        let visibleMaxX = waterfallScrollOffset + waterfallLayer.bounds.width
        if column.containerLayer.frame.maxX < visibleMinX + WaterfallMetrics.gap {
            return "left"
        }
        if column.containerLayer.frame.minX > visibleMaxX - WaterfallMetrics.gap {
            return "right"
        }
        return "visible"
    }

    private func appShelfVisualIconSize(forBaseIconSize iconSize: CGFloat, selected: Bool, hovered: Bool) -> CGFloat {
        guard selected || hovered else { return iconSize }
        return AppShelfMetrics.selectedIconSize
    }

    private func appShelfZPosition(selected: Bool, hovered: Bool) -> CGFloat {
        switch (selected, hovered) {
        case (true, true):
            return 30
        case (true, false):
            return 20
        case (false, true):
            return 10
        case (false, false):
            return 0
        }
    }

    private func appShelfBackgroundColor(selected: Bool, hovered: Bool, spaceFocused: Bool) -> NSColor {
        if selected {
            return NSColor.controlAccentColor.withAlphaComponent(0.12)
        }
        if hovered {
            return NSColor.systemFill.withAlphaComponent(0.12)
        }
        if spaceFocused {
            return NSColor.keyboardFocusIndicatorColor.withAlphaComponent(0.10)
        }
        return .clear
    }

    private func appShelfBadgeText(for item: AppShelfItemLayers) -> String {
        if let _ = activeSpaceFocusID {
            let count = spaceFocusWindowCount(for: item.item.appGroupIndex)
            guard count > 0 else { return "" }

            let countText = count > 9 ? "9+" : "\(count)"
            switch spaceFocusDirection(for: item.item.appGroupIndex) {
            case "left":
                return "<\(countText)"
            case "right":
                return "\(countText)>"
            default:
                return countText
            }
        }

        return item.item.windowCount > 1 ? "\(item.item.windowCount)" : ""
    }

    private var appShelfMaxScrollOffset: CGFloat {
        max(0, appShelfContentWidth - shelfLayer.bounds.width)
    }

    private func clampedAppShelfOffset(_ offset: CGFloat) -> CGFloat {
        min(max(0, offset), appShelfMaxScrollOffset)
    }

    private func layoutWaterfallColumns() {
        guard !waterfallColumns.isEmpty else {
            waterfallContentWidth = waterfallLayer.bounds.width
            waterfallScrollOffset = 0
            waterfallContentLayer.frame = waterfallLayer.bounds
            return
        }

        let columnWidth = waterfallColumnWidth()
        let totalWidth = WaterfallMetrics.columnPadding * 2
            + CGFloat(waterfallColumns.count) * columnWidth
            + CGFloat(max(0, waterfallColumns.count - 1)) * WaterfallMetrics.gap
        waterfallContentWidth = max(waterfallLayer.bounds.width, totalWidth)
        waterfallScrollOffset = clampedWaterfallAlignmentOffset(waterfallScrollOffset)
        waterfallContentLayer.frame = CGRect(
            x: -waterfallScrollOffset,
            y: 0,
            width: waterfallContentWidth,
            height: waterfallLayer.bounds.height
        )

        var x = WaterfallMetrics.columnPadding
        for column in waterfallColumns {
            column.containerLayer.frame = CGRect(
                x: x,
                y: 0,
                width: columnWidth,
                height: waterfallLayer.bounds.height
            )
            layoutWaterfallColumn(column)
            x += columnWidth + WaterfallMetrics.gap
        }
    }

    private func layoutWaterfallColumn(_ column: WaterfallColumnLayers) {
        let bounds = column.containerLayer.bounds
        let isSpaceFocused = spaceFocusWindowCount(for: column.column.appGroupIndex) > 0
        column.containerLayer.borderColor = (isSpaceFocused
            ? NSColor.separatorColor.withAlphaComponent(0.38)
            : NSColor.separatorColor.withAlphaComponent(0.24)
        ).cgColor
        column.containerLayer.borderWidth = 1
        column.headerLayer.frame = CGRect(
            x: 0,
            y: bounds.height - WaterfallMetrics.headerHeight,
            width: bounds.width,
            height: WaterfallMetrics.headerHeight
        )
        column.headerLayer.backgroundColor = (isSpaceFocused
            ? NSColor.systemFill.withAlphaComponent(0.10)
            : NSColor.controlBackgroundColor.withAlphaComponent(0.52)
        ).cgColor
        column.appNameLayer.frame = CGRect(
            x: WaterfallMetrics.columnPadding,
            y: bounds.height - 24,
            width: max(1, bounds.width - 64),
            height: 16
        )
        column.countLayer.frame = CGRect(
            x: bounds.width - 48,
            y: bounds.height - 24,
            width: 36,
            height: 16
        )

        let appGroupIndex = column.column.appGroupIndex
        let verticalOffset = clampedWaterfallColumnOffset(
            waterfallColumnScrollOffsets[appGroupIndex] ?? 0,
            appGroupIndex: appGroupIndex
        )
        waterfallColumnScrollOffsets[appGroupIndex] = verticalOffset

        let cardWidth = max(1, bounds.width - WaterfallMetrics.columnPadding * 2)
        let firstCardTop = bounds.height
            - WaterfallMetrics.headerHeight
            - WaterfallMetrics.columnPadding
            + verticalOffset

        for card in column.cards {
            let cardIndex = card.item.windowIndex
            let y = firstCardTop
                - WaterfallMetrics.cardHeight
                - CGFloat(cardIndex) * (WaterfallMetrics.cardHeight + WaterfallMetrics.cardGap)
            card.containerLayer.frame = CGRect(
                x: WaterfallMetrics.columnPadding,
                y: y,
                width: cardWidth,
                height: WaterfallMetrics.cardHeight
            )
            layoutWaterfallCard(card)
        }
    }

    private func layoutWaterfallCard(_ card: WaterfallCardLayers) {
        let bounds = card.containerLayer.bounds
        let isSelected = card.item.window.id == effectiveSelection?.windowID
        let isHovered = card.item.window.id == hoveredWindowID
        applyWaterfallCardVisualState(card, selected: isSelected, hovered: isHovered)

        let thumbnailWidth = max(90, min(116, bounds.width * 0.44))
        card.thumbnailLayer.frame = CGRect(
            x: 10,
            y: 12,
            width: thumbnailWidth,
            height: bounds.height - 24
        )
        card.appIconLayer.frame = CGRect(x: 18, y: bounds.height - 38, width: 22, height: 22)
        card.titleLayer.frame = CGRect(
            x: thumbnailWidth + 22,
            y: bounds.height - 31,
            width: max(1, bounds.width - thumbnailWidth - 34),
            height: 16
        )
        card.metaLayer.frame = CGRect(
            x: thumbnailWidth + 22,
            y: bounds.height - 51,
            width: max(1, bounds.width - thumbnailWidth - 34),
            height: 14
        )
        card.stateLayer.frame = CGRect(
            x: thumbnailWidth + 22,
            y: 12,
            width: max(1, bounds.width - thumbnailWidth - 34),
            height: 14
        )
        card.shineLayer.frame = CGRect(
            x: -bounds.width * 0.18,
            y: 0,
            width: max(36, min(96, bounds.width * 0.24)),
            height: bounds.height
        )
    }

    private func applyWaterfallCardVisualState(_ card: WaterfallCardLayers, selected: Bool, hovered: Bool) {
        let isSpaceFocused = card.item.primarySpaceID == activeSpaceFocusID
        card.containerLayer.backgroundColor = (selected
            ? NSColor.windowBackgroundColor.withAlphaComponent(0.94)
            : hovered
                ? NSColor.systemFill.withAlphaComponent(0.13)
                : isSpaceFocused
                    ? NSColor.windowBackgroundColor.withAlphaComponent(0.88)
                : NSColor.windowBackgroundColor.withAlphaComponent(0.82)
        ).cgColor
        card.containerLayer.borderColor = (selected
            ? NSColor.controlAccentColor.withAlphaComponent(0.52)
            : hovered
                ? NSColor.separatorColor.withAlphaComponent(0.46)
                : isSpaceFocused
                    ? NSColor.separatorColor.withAlphaComponent(0.38)
                : NSColor.separatorColor.withAlphaComponent(0.28)
        ).cgColor
        card.containerLayer.borderWidth = selected ? 1.5 : 1
        card.containerLayer.shadowColor = NSColor.black.cgColor
        card.containerLayer.shadowOpacity = selected ? 0.20 : hovered ? 0.08 : 0
        card.containerLayer.shadowRadius = selected ? 18 : hovered ? 10 : 0
        card.containerLayer.shadowOffset = selected
            ? CGSize(width: 0, height: -5)
            : hovered
                ? CGSize(width: 0, height: -2)
                : .zero
        card.containerLayer.zPosition = selected ? 20 : hovered ? 10 : 0
        card.shineLayer.opacity = selected ? 1 : 0
    }

    private func waterfallColumnWidth() -> CGFloat {
        guard waterfallColumns.count > 0 else { return WaterfallMetrics.columnWidth }

        let visibleColumns = min(4, max(1, waterfallColumns.count))
        let fittingWidth = (
            waterfallLayer.bounds.width
                - WaterfallMetrics.columnPadding * 2
                - CGFloat(max(0, visibleColumns - 1)) * WaterfallMetrics.gap
        ) / CGFloat(visibleColumns)
        return max(
            WaterfallMetrics.columnMinWidth,
            min(WaterfallMetrics.columnMaxWidth, min(WaterfallMetrics.columnWidth, fittingWidth))
        )
    }

    private var waterfallMaxScrollOffset: CGFloat {
        max(0, waterfallContentWidth - waterfallLayer.bounds.width)
    }

    private func clampedWaterfallOffset(_ offset: CGFloat) -> CGFloat {
        min(max(0, offset), waterfallMaxScrollOffset)
    }

    private func waterfallMaxVerticalScrollOffset(for appGroupIndex: Int) -> CGFloat {
        guard
            let column = waterfallColumns.first(where: { $0.column.appGroupIndex == appGroupIndex })
        else {
            return 0
        }

        let visibleHeight = max(
            1,
            waterfallLayer.bounds.height
                - WaterfallMetrics.headerHeight
                - WaterfallMetrics.columnPadding * 2
        )
        let contentHeight = CGFloat(column.cards.count) * WaterfallMetrics.cardHeight
            + CGFloat(max(0, column.cards.count - 1)) * WaterfallMetrics.cardGap
        return max(0, contentHeight - visibleHeight)
    }

    private func clampedWaterfallColumnOffset(_ offset: CGFloat, appGroupIndex: Int) -> CGFloat {
        min(max(0, offset), waterfallMaxVerticalScrollOffset(for: appGroupIndex))
    }

    private func waterfallMetaText(for card: QuickSwitchWindowCardViewModel) -> String {
        card.primarySpaceLabel ?? "No Space"
    }

    private func waterfallStateText(for card: QuickSwitchWindowCardViewModel) -> String {
        var states: [String] = []
        if card.window.isMinimized {
            states.append("Minimized")
        }
        if card.window.isFullscreen {
            states.append("Fullscreen")
        }
        if card.window.identifierSource == .syntheticAX {
            states.append("AX")
        }

        return states.joined(separator: " / ")
    }

    private func spaceColor(for space: QuickSwitchSpaceViewModel) -> NSColor {
        if space.isCurrent {
            return NSColor.windowBackgroundColor.withAlphaComponent(0.76)
        }
        if space.windowCount > 0 {
            return NSColor.controlBackgroundColor.withAlphaComponent(0.56)
        }

        return NSColor.controlBackgroundColor.withAlphaComponent(0.26)
    }

    private func makeFullscreenMarkerLayer(for space: QuickSwitchSpaceViewModel) -> CALayer? {
        guard space.type == .fullscreen else { return nil }

        let layer = CALayer()
        layer.cornerRadius = 1.5
        layer.backgroundColor = NSColor.secondaryLabelColor.withAlphaComponent(space.isCurrent ? 0.46 : 0.32).cgColor
        return layer
    }

    private func makeTextLayer(
        string: String,
        fontSize: CGFloat,
        weight: NSFont.Weight,
        color: NSColor,
        alignment: CATextLayerAlignmentMode = .left
    ) -> CATextLayer {
        let textLayer = CATextLayer()
        textLayer.contentsScale = backingScaleFactor
        textLayer.string = string
        textLayer.font = NSFont.systemFont(ofSize: fontSize, weight: weight)
        textLayer.fontSize = fontSize
        textLayer.foregroundColor = color.cgColor
        textLayer.alignmentMode = alignment
        textLayer.truncationMode = .middle
        return textLayer
    }

    private func makeWindowBlocks(count: Int, space: QuickSwitchSpaceViewModel) -> [CALayer] {
        guard count > 0 else { return [] }

        return (0..<count).map { _ in
            let layer = CALayer()
            layer.cornerRadius = 3
            layer.backgroundColor = (space.type == .fullscreen
                ? NSColor.labelColor.withAlphaComponent(0.20)
                : NSColor.labelColor.withAlphaComponent(0.18)
            ).cgColor
            return layer
        }
    }

    private func appIdentifierText(for appNames: [String]) -> String {
        var identifiers = appNames.prefix(3).compactMap { name -> String? in
            let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
            return trimmed.first.map { String($0) }
        }

        if appNames.count > 3 {
            identifiers.append("+\(appNames.count - 3)")
        }

        return identifiers.joined(separator: " ")
    }

    private func columnSelectionHistoryReports() -> [[String: Int]] {
        columnSelectionHistory
            .sorted { $0.key < $1.key }
            .map { appGroupIndex, windowIndex in
                [
                    "appGroupIndex": appGroupIndex,
                    "windowIndex": windowIndex
                ]
            }
    }

    private func appShelfItemReports() -> [[String: Any]] {
        appShelfItems.enumerated().map { index, item in
            let visibleFrame = item.containerLayer.frame.offsetBy(dx: appShelfContentLayer.frame.minX, dy: 0)
            return [
                "index": index,
                "name": item.item.app.name,
                "bundleIdentifier": item.item.app.bundleIdentifier,
                "windowCount": item.item.windowCount,
                "spaceFocusWindowCount": spaceFocusWindowCount(for: item.item.appGroupIndex),
                "spaceFocusDirection": spaceFocusDirection(for: item.item.appGroupIndex),
                "isSelected": item.item.appGroupIndex == effectiveSelection?.appGroupIndex,
                "isHovered": item.item.appGroupIndex == effectiveHoveredAppGroupIndex,
                "isSpaceFocused": spaceFocusWindowCount(for: item.item.appGroupIndex) > 0,
                "visualStates": appShelfVisualStates(for: item),
                "zPosition": Double(item.containerLayer.zPosition),
                "hasMinimizedWindows": item.item.hasMinimizedWindows,
                "hasFullscreenWindows": item.item.hasFullscreenWindows,
                "frame": dictionary(from: item.containerLayer.frame),
                "visibleFrame": dictionary(from: visibleFrame),
                "iconFrame": dictionary(from: item.iconLayer.frame),
                "labelFrame": dictionary(from: item.labelLayer.frame),
                "labelTruncationMode": "middle",
                "badgeVisible": !item.badgeLayer.isHidden,
                "badgeText": item.badgeLayer.string ?? ""
            ] as [String: Any]
        }
    }

    private func appShelfVisualStates(for item: AppShelfItemLayers) -> [String] {
        var states: [String] = []
        if item.item.appGroupIndex == effectiveSelection?.appGroupIndex {
            states.append("selected")
        }
        if item.item.appGroupIndex == effectiveHoveredAppGroupIndex {
            states.append("hover")
        }
        if spaceFocusWindowCount(for: item.item.appGroupIndex) > 0 {
            states.append("spaceFocused")
            let direction = spaceFocusDirection(for: item.item.appGroupIndex)
            if direction != "none" {
                states.append("spaceFocusDirection:\(direction)")
            }
        }
        return states
    }

    private func waterfallColumnReports() -> [[String: Any]] {
        waterfallColumns.map { column in
            let visibleFrame = column.containerLayer.frame.offsetBy(dx: waterfallContentLayer.frame.minX, dy: 0)
            let appGroupIndex = column.column.appGroupIndex

            return [
                "appGroupIndex": appGroupIndex,
                "appName": column.column.app.name,
                "bundleIdentifier": column.column.app.bundleIdentifier,
                "windowCount": column.column.windows.count,
                "spaceFocusWindowCount": spaceFocusWindowCount(for: appGroupIndex),
                "isSpaceFocused": spaceFocusWindowCount(for: appGroupIndex) > 0,
                "spaceFocusDirection": spaceFocusDirection(for: appGroupIndex),
                "frame": dictionary(from: column.containerLayer.frame),
                "visibleFrame": dictionary(from: visibleFrame),
                "verticalScrollOffset": Double(waterfallColumnScrollOffsets[appGroupIndex] ?? 0),
                "maxVerticalScrollOffset": Double(waterfallMaxVerticalScrollOffset(for: appGroupIndex)),
                "cards": waterfallCardReports(for: column)
            ] as [String: Any]
        }
    }

    private func appColumnAlignmentReports() -> [[String: Any]] {
        appShelfItems.compactMap { item in
            guard let column = waterfallColumns.first(where: { $0.column.appGroupIndex == item.item.appGroupIndex }) else {
                return nil
            }

            let appIconCenterX = item.containerLayer.frame.minX
                + item.iconLayer.frame.midX
                + appShelfContentLayer.frame.minX
            let visibleColumnFrame = column.containerLayer.frame.offsetBy(dx: waterfallContentLayer.frame.minX, dy: 0)
            let columnCenterX = visibleColumnFrame.midX
            let deltaX = columnCenterX - appIconCenterX
            let rightBlankWidth = max(0, waterfallLayer.bounds.width - visibleColumnFrame.maxX)
            let leftBlankWidth = max(0, visibleColumnFrame.minX)

            return [
                "appGroupIndex": item.item.appGroupIndex,
                "appName": item.item.app.name,
                "appIconCenterX": Double(appIconCenterX),
                "columnCenterX": Double(columnCenterX),
                "deltaX": Double(deltaX),
                "absDeltaX": Double(abs(deltaX)),
                "tolerance": Double(WaterfallAlignmentMetrics.tolerance),
                "passed": abs(deltaX) <= WaterfallAlignmentMetrics.tolerance,
                "waterfallScrollOffset": Double(waterfallScrollOffset),
                "waterfallMaxScrollOffset": Double(waterfallMaxScrollOffset),
                "waterfallAlignmentMinScrollOffset": Double(waterfallAlignmentScrollRange.lowerBound),
                "waterfallAlignmentMaxScrollOffset": Double(waterfallAlignmentScrollRange.upperBound),
                "rightBlankWidth": Double(rightBlankWidth),
                "leftBlankWidth": Double(leftBlankWidth),
                "alignmentClampedReason": alignmentClampedReason(for: item, column: column)
            ] as [String: Any]
        }
    }

    private func alignmentClampedReason(for item: AppShelfItemLayers, column: WaterfallColumnLayers) -> String {
        let targetOffset = targetWaterfallOffsetAligning(column: column, to: item)
        let range = waterfallAlignmentScrollRange
        if targetOffset < range.lowerBound - WaterfallAlignmentMetrics.tolerance {
            return "leading"
        }
        if targetOffset > range.upperBound + WaterfallAlignmentMetrics.tolerance {
            return "trailing"
        }
        return "none"
    }

    private func waterfallCardReports(for column: WaterfallColumnLayers) -> [[String: Any]] {
        column.cards.map { card in
            let visibleFrame = card.containerLayer.frame.offsetBy(
                dx: column.containerLayer.frame.minX + waterfallContentLayer.frame.minX,
                dy: column.containerLayer.frame.minY
            )
            let screenshotSource = screenshotSourcesByWindowID[card.item.window.id]

            var report = [
                "appGroupIndex": card.item.appGroupIndex,
                "windowIndex": card.item.windowIndex,
                "globalIndex": card.item.globalIndex,
                "windowID": Int(card.item.window.id),
                "titleHash": DevelopmentDiagnostics.stableFingerprint(card.item.window.title),
                "titleLength": card.item.window.title.count,
                "titleIsEmpty": card.item.window.title.isEmpty,
                "primarySpaceID": card.item.primarySpaceID ?? NSNull(),
                "primarySpaceLabel": card.item.primarySpaceLabel ?? NSNull(),
                "isMinimized": card.item.window.isMinimized,
                "isFullscreen": card.item.window.isFullscreen,
                "identifierSource": "\(card.item.window.identifierSource)",
                "isSelected": card.item.window.id == effectiveSelection?.windowID,
                "visualStates": waterfallCardVisualStates(for: card),
                "thumbnailStrategy": thumbnailStrategyString(for: card.item.window),
                "screenshotSource": screenshotSourceString(screenshotSource, for: card.item.window),
                "screenshotFallbackReason": screenshotFallbackReasonString(screenshotSource),
                "screenshotNotRequestedReason": screenshotSkippedReasonsByWindowID[card.item.window.id] ?? NSNull(),
                "thumbnailFrame": dictionary(from: card.thumbnailLayer.frame),
                "appIconFrame": dictionary(from: card.appIconLayer.frame),
                "shineVisible": card.shineLayer.opacity > 0,
                "zPosition": Double(card.containerLayer.zPosition),
                "frame": dictionary(from: card.containerLayer.frame),
                "visibleFrame": dictionary(from: visibleFrame),
                "titleTruncationMode": "middle"
            ] as [String: Any]
            if DevelopmentDiagnostics.includesSensitiveFields {
                report["title"] = card.item.window.title
            }
            return report
        }
    }

    private func waterfallCardsByWindowID() -> [UInt32: WaterfallCardLayers] {
        var cards: [UInt32: WaterfallCardLayers] = [:]
        for column in waterfallColumns {
            for card in column.cards {
                cards[card.item.window.id] = card
            }
        }
        return cards
    }

    private var allWaterfallWindows: [AlignerWindow] {
        currentViewModel?.waterfallColumns.flatMap { column in
            column.windows.map(\.window)
        } ?? []
    }

    private var screenshotEligibleWindows: [AlignerWindow] {
        allWaterfallWindows.filter(Self.shouldRequestScreenshot)
    }

    private var screenshotPendingWindows: [AlignerWindow] {
        screenshotEligibleWindows.filter { window in
            screenshotSourcesByWindowID[window.id] == nil
                && screenshotSkippedReasonsByWindowID[window.id] == nil
        }
    }

    private static func shouldRequestScreenshot(for window: AlignerWindow) -> Bool {
        switch ThumbnailPolicy.preferredStrategy(for: window.app.category) {
        case .screenshotPreferred:
            return true
        case .skeletonPreferred, .fallbackSkeleton:
            return false
        }
    }

    private func thumbnailStrategyString(for window: AlignerWindow) -> String {
        if let source = screenshotSourcesByWindowID[window.id] {
            return screenshotSourceString(source, for: window)
        }

        if let skippedReason = screenshotSkippedReasonsByWindowID[window.id] {
            return skippedReason == "skeletonPreferred" ? "skeletonPreferred" : "skeleton"
        }

        switch ThumbnailPolicy.preferredStrategy(for: window.app.category) {
        case .skeletonPreferred:
            return "skeletonPreferred"
        case .screenshotPreferred:
            return "pendingScreenshot"
        case .fallbackSkeleton:
            return "skeleton"
        }
    }

    private func screenshotSourceString(_ source: ScreenshotResolutionSource?, for window: AlignerWindow) -> String {
        guard let source else {
            return Self.shouldRequestScreenshot(for: window)
                && screenshotSkippedReasonsByWindowID[window.id] == nil
                ? "pending"
                : "notRequested"
        }

        switch source {
        case .realScreenshot:
            return "realScreenshot"
        case .skeletonFallback:
            return "skeletonFallback"
        }
    }

    private func screenshotFallbackReasonString(_ source: ScreenshotResolutionSource?) -> Any {
        guard case .skeletonFallback(let reason) = source else {
            return NSNull()
        }

        return reason.diagnosticDescription
    }

    private func waterfallCardVisualStates(for card: WaterfallCardLayers) -> [String] {
        var states: [String] = []
        if card.item.window.id == effectiveSelection?.windowID {
            states.append("selected")
        }
        if card.item.window.id == hoveredWindowID {
            states.append("hover")
        }
        if card.item.primarySpaceID == activeSpaceFocusID {
            states.append("spaceFocused")
        }
        if card.item.window.isMinimized {
            states.append("minimized")
        }
        if card.item.window.isFullscreen {
            states.append("fullscreen")
        }
        return states
    }

    private var backingScaleFactor: CGFloat {
        window?.backingScaleFactor ?? NSScreen.main?.backingScaleFactor ?? 2
    }

    private func spaceLaneSegmentReports() -> [[String: Any]] {
        currentViewModel?.displays.flatMap { display in
            display.spaces.compactMap { space in
                guard let segment = spaceLaneSegments.first(where: { $0.space.id == space.id }) else {
                    return nil
                }
                let visibleFrame = segment.containerLayer.frame.offsetBy(dx: spaceLaneContentLayer.frame.minX, dy: 0)
                return [
                    "displayUUID": display.displayUUID,
                    "displayLabel": display.displayLabel,
                    "label": space.label,
                    "type": spaceTypeName(space.type),
                    "visualStates": visualStates(for: space),
                    "fullscreenMarkerVisible": segment.fullscreenMarkerLayer != nil,
                    "frame": dictionary(from: segment.containerLayer.frame),
                    "visibleFrame": dictionary(from: visibleFrame),
                    "isCurrent": space.isCurrent,
                    "isHovered": space.id == hoveredSpaceID,
                    "isFocused": space.id == activeSpaceFocusID,
                    "windowCount": space.windowCount,
                    "appCount": space.appCount,
                    "appNames": space.appNames
                ] as [String: Any]
            }
        } ?? []
    }

    private func visualStates(for space: QuickSwitchSpaceViewModel) -> [String] {
        var states: [String] = []
        if space.isCurrent {
            states.append("current")
        }
        if space.id == hoveredSpaceID {
            states.append("hover")
        }
        if space.id == activeSpaceFocusID {
            states.append("focused")
        }
        if space.type == .fullscreen {
            states.append("fullscreen")
        }
        return states
    }

    private func spaceTypeName(_ type: AlignerSpaceType) -> String {
        switch type {
        case .user:
            return "user"
        case .fullscreen:
            return "fullscreen"
        case .system:
            return "system"
        case .unknown(let rawValue):
            return "unknown(\(rawValue))"
        }
    }

    private func dictionary(from rect: CGRect) -> [String: Double] {
        [
            "x": Double(rect.origin.x),
            "y": Double(rect.origin.y),
            "width": Double(rect.width),
            "height": Double(rect.height)
        ]
    }
}
