Private/Presentation/HistoricalChart.ps1

function Update-HistoricalChartPlot {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$View
    )

    $canvas = $View.PlotCanvas
    $canvas.Children.Clear()
    $width = if ($canvas.ActualWidth -gt 0) { $canvas.ActualWidth } else { 640.0 }
    $height = if ($canvas.ActualHeight -gt 0) { $canvas.ActualHeight } else { 260.0 }
    $margins = Get-HistoricalChartMargins
    $marginLeft = $margins.Left
    $marginRight = $margins.Right
    $marginTop = $margins.Top
    $marginBottom = $margins.Bottom
    $plotWidth = [math]::Max(1.0, $width - $marginLeft - $marginRight)
    $plotHeight = [math]::Max(1.0, $height - $marginTop - $marginBottom)

    $observations = @($View.Series.observations)
    if ($observations.Count -eq 0) {
        for ($lineIndex = 0; $lineIndex -le 4; $lineIndex++) {
            Add-HistoricalChartLine -Canvas $canvas -X1 $marginLeft -X2 ($marginLeft + $plotWidth) `
                -Y1 ($marginTop + ($plotHeight * $lineIndex / 4.0)) -Y2 ($marginTop + ($plotHeight * $lineIndex / 4.0))
        }
        $emptyText = [System.Windows.Controls.TextBlock]::new()
        $emptyText.Text = if ($View.Series.reason) { [string]$View.Series.reason } else { 'No history is available for this range.' }
        $emptyText.Foreground = [System.Windows.Media.Brushes]::LightGray
        $emptyText.TextWrapping = [System.Windows.TextWrapping]::Wrap
        [System.Windows.Controls.Canvas]::SetLeft($emptyText, 16)
        [System.Windows.Controls.Canvas]::SetTop($emptyText, 16)
        $canvas.Children.Add($emptyText) | Out-Null
        return
    }

    $observationTimes = @($View.ObservationTimesUtc)
    if ($observationTimes.Count -ne $observations.Count) {
        $observationTimes = @(Get-HistoricalObservationTimestamps -Observations $observations)
        $View.ObservationTimesUtc = $observationTimes
    }
    $firstTicks = $observationTimes[0].Ticks
    $timeSpanTicks = [double]($observationTimes[-1].Ticks - $firstTicks)
    $minimum = [double]::PositiveInfinity
    $maximum = [double]::NegativeInfinity
    foreach ($observation in $observations) {
        $value = [double]$observation.value
        if ($value -lt $minimum) { $minimum = $value }
        if ($value -gt $maximum) { $maximum = $value }
    }
    if ($maximum -le $minimum) {
        $padding = [math]::Max([math]::Abs($maximum) * 0.01, 0.01)
        $minimum -= $padding
        $maximum += $padding
    }
    else {
        $padding = ($maximum - $minimum) * 0.08
        $minimum -= $padding
        $maximum += $padding
    }

    $pointCount = $observations.Count
    $visibleSpan = 1.0 / [math]::Max(1.0, [double]$View.ZoomFactor)
    $maximumPanOffset = [math]::Max(0.0, 1.0 - $visibleSpan)
    $panOffset = [math]::Min([math]::Max(0.0, [double]$View.PanOffset), $maximumPanOffset)
    $startPosition = $panOffset
    $endPosition = $panOffset + $visibleSpan
    $segments = [System.Collections.Generic.List[System.Windows.Shapes.Polyline]]::new()
    $gapLookup = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal)
    foreach ($gap in $View.Series.gaps) {
        $afterTicks = ([DateTimeOffset]$gap.afterUtc).ToUniversalTime().Ticks
        $beforeTicks = ([DateTimeOffset]$gap.beforeUtc).ToUniversalTime().Ticks
        [void]$gapLookup.Add("$afterTicks|$beforeTicks")
    }
    $polyline = $null
    $inspectedPoint = $null
    $hasInspection = $null -ne $View.PSObject.Properties['HasInspection'] -and [bool]$View.HasInspection
    for ($index = 0; $index -lt $pointCount; $index++) {
        $position = if ($pointCount -eq 1 -or $timeSpanTicks -le 0) {
            0.5
        }
        else {
            ($observationTimes[$index].Ticks - $firstTicks) / $timeSpanTicks
        }
        if ($position -lt $startPosition -or $position -gt $endPosition) {
            if ($null -ne $polyline -and $polyline.Points.Count -gt 0) {
                $segments.Add($polyline)
                $polyline = $null
            }
            continue
        }
        if ($index -gt 0 -and $gapLookup.Count -gt 0) {
            $previousAtUtc = $observationTimes[$index - 1]
            $currentAtUtc = $observationTimes[$index]
            $hasGap = $gapLookup.Contains("$($previousAtUtc.Ticks)|$($currentAtUtc.Ticks)")
            if ($hasGap -and $null -ne $polyline) {
                $segments.Add($polyline)
                $polyline = $null
            }
        }
        if ($null -eq $polyline) {
            $polyline = [System.Windows.Shapes.Polyline]::new()
            $polyline.Stroke = [System.Windows.Media.Brushes]::LightGreen
            $polyline.StrokeThickness = 2
            $polyline.SnapsToDevicePixels = $true
        }
        $x = $marginLeft + (($position - $startPosition) / $visibleSpan * $plotWidth)
        $value = [double]$observations[$index].value
        $y = $marginTop + (($maximum - $value) / ($maximum - $minimum) * $plotHeight)
        $polyline.Points.Add([System.Windows.Point]::new($x, $y))
        if ($hasInspection -and $index -eq [int]$View.InspectionIndex) {
            $inspectedPoint = [System.Windows.Point]::new($x, $y)
        }
    }
    if ($null -ne $polyline -and $polyline.Points.Count -gt 0) {
        $segments.Add($polyline)
    }
    foreach ($segment in $segments) {
        $canvas.Children.Add($segment) | Out-Null
    }

    # Y axis: labelled horizontal gridlines.
    $culture = [System.Globalization.CultureInfo]::InvariantCulture
    $valueStep = ($maximum - $minimum) / 4.0
    $decimals = [int][math]::Min(6, [math]::Max(0, [math]::Ceiling(-[math]::Log10($valueStep)) + 1))
    for ($lineIndex = 0; $lineIndex -le 4; $lineIndex++) {
        $y = $marginTop + ($plotHeight * $lineIndex / 4.0)
        Add-HistoricalChartLine -Canvas $canvas -X1 $marginLeft -X2 ($marginLeft + $plotWidth) -Y1 $y -Y2 $y
        $tickValue = $maximum - ($valueStep * $lineIndex)
        Add-HistoricalChartText -Canvas $canvas -Text $tickValue.ToString("N$decimals", $culture) `
            -Left 0 -Top ($y - 7) -Width ($marginLeft - 6) -Alignment Right
    }

    # X axis: baseline plus evenly spaced date ticks across the visible window.
    $axisY = $marginTop + $plotHeight
    Add-HistoricalChartLine -Canvas $canvas -X1 $marginLeft -X2 ($marginLeft + $plotWidth) -Y1 $axisY -Y2 $axisY `
        -Brush ([System.Windows.Media.Brushes]::SlateGray) -Thickness 1
    Add-HistoricalChartLine -Canvas $canvas -X1 $marginLeft -X2 $marginLeft -Y1 $marginTop -Y2 $axisY `
        -Brush ([System.Windows.Media.Brushes]::SlateGray) -Thickness 1
    $visibleStartTicks = $firstTicks + ($timeSpanTicks * $startPosition)
    $visibleTicks = $timeSpanTicks * $visibleSpan
    $dateFormat = if ($visibleTicks -le [TimeSpan]::FromDays(2).Ticks) { 'dd MMM HH:mm' }
    elseif ($visibleTicks -le [TimeSpan]::FromDays(400).Ticks) { 'dd MMM' }
    else { 'MMM yyyy' }
    $tickCount = if ($timeSpanTicks -le 0) { 0 } else { [int][math]::Max(1, [math]::Min(8, [math]::Floor($plotWidth / 110.0))) }
    $tickFractions = if ($tickCount -eq 0) { @(0.5) } else { 0..$tickCount | ForEach-Object { $_ / [double]$tickCount } }
    foreach ($fraction in $tickFractions) {
        $x = $marginLeft + ($fraction * $plotWidth)
        $tickTime = if ($tickCount -eq 0) { $observationTimes[0] }
        else { [DateTimeOffset]::new([long]($visibleStartTicks + ($visibleTicks * $fraction)), [TimeSpan]::Zero) }
        Add-HistoricalChartLine -Canvas $canvas -X1 $x -X2 $x -Y1 $axisY -Y2 ($axisY + 4) `
            -Brush ([System.Windows.Media.Brushes]::SlateGray) -Thickness 1
        $labelLeft = [math]::Min([math]::Max(0.0, $x - 45.0), $width - 90.0)
        Add-HistoricalChartText -Canvas $canvas -Text $tickTime.ToString($dateFormat, $culture) `
            -Left $labelLeft -Top ($axisY + 6) -Width 90 -Alignment Center
    }
    Add-HistoricalChartText -Canvas $canvas -Text 'Date (UTC)' -Left $marginLeft -Top ($axisY + 22) `
        -Width $plotWidth -Alignment Center -Brush ([System.Windows.Media.Brushes]::Gray)
    if (-not [string]::IsNullOrWhiteSpace([string]$View.Series.unit)) {
        Add-HistoricalChartText -Canvas $canvas -Text ([string]$View.Series.unit) -Left 4 -Top 0 `
            -Width ($marginLeft + 120) -Alignment Left -Brush ([System.Windows.Media.Brushes]::Gray)
    }

    if ($null -ne $inspectedPoint) {
        $crosshairBrush = [System.Windows.Media.Brushes]::Gold
        foreach ($coordinates in @(
                @($inspectedPoint.X, $inspectedPoint.X, $marginTop, $axisY),
                @($marginLeft, ($marginLeft + $plotWidth), $inspectedPoint.Y, $inspectedPoint.Y))) {
            $guide = [System.Windows.Shapes.Line]::new()
            $guide.X1 = $coordinates[0]; $guide.X2 = $coordinates[1]
            $guide.Y1 = $coordinates[2]; $guide.Y2 = $coordinates[3]
            $guide.Stroke = $crosshairBrush
            $guide.StrokeThickness = 1
            $guide.StrokeDashArray = [System.Windows.Media.DoubleCollection]::new([double[]]@(4, 3))
            $guide.IsHitTestVisible = $false
            $guide.Tag = 'inspection-crosshair'
            $canvas.Children.Add($guide) | Out-Null
        }
        $marker = [System.Windows.Shapes.Ellipse]::new()
        $marker.Width = 8; $marker.Height = 8
        $marker.Fill = $crosshairBrush
        $marker.Stroke = [System.Windows.Media.Brushes]::Black
        $marker.StrokeThickness = 1
        $marker.IsHitTestVisible = $false
        $marker.Tag = 'inspection-marker'
        [System.Windows.Controls.Canvas]::SetLeft($marker, $inspectedPoint.X - 4)
        [System.Windows.Controls.Canvas]::SetTop($marker, $inspectedPoint.Y - 4)
        $canvas.Children.Add($marker) | Out-Null
    }

    # Legend (top-right): series swatch, name and unit.
    $legend = [System.Windows.Controls.StackPanel]::new()
    $legend.Orientation = [System.Windows.Controls.Orientation]::Horizontal
    $legend.Background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromArgb(0xCC, 0x11, 0x1A, 0x2B))
    $legend.IsHitTestVisible = $false
    $swatch = [System.Windows.Shapes.Rectangle]::new()
    $swatch.Width = 16; $swatch.Height = 3
    $swatch.Fill = [System.Windows.Media.Brushes]::LightGreen
    $swatch.Margin = [System.Windows.Thickness]::new(6, 0, 6, 0)
    $swatch.VerticalAlignment = [System.Windows.VerticalAlignment]::Center
    $legendText = [System.Windows.Controls.TextBlock]::new()
    $legendText.Text = '{0}{1}' -f $(if ($View.Series.symbol) { $View.Series.symbol } else { $View.Series.displayName }),
        $(if ($View.Series.interval) { ", $($View.Series.interval) interval" } else { '' })
    $legendText.Foreground = [System.Windows.Media.Brushes]::LightGray
    $legendText.FontSize = 11
    $legendText.Margin = [System.Windows.Thickness]::new(0, 2, 6, 2)
    $legend.Children.Add($swatch) | Out-Null
    $legend.Children.Add($legendText) | Out-Null
    $legend.Measure([System.Windows.Size]::new([double]::PositiveInfinity, [double]::PositiveInfinity))
    [System.Windows.Controls.Canvas]::SetLeft($legend, [math]::Max($marginLeft, $marginLeft + $plotWidth - $legend.DesiredSize.Width - 6))
    [System.Windows.Controls.Canvas]::SetTop($legend, $marginTop + 4)
    $canvas.Children.Add($legend) | Out-Null
}

function Get-HistoricalChartMargins {
    @{ Left = 70.0; Right = 16.0; Top = 20.0; Bottom = 44.0 }
}

function Add-HistoricalChartLine {
    param(
        [System.Windows.Controls.Canvas]$Canvas,
        [double]$X1, [double]$X2, [double]$Y1, [double]$Y2,
        [System.Windows.Media.Brush]$Brush = [System.Windows.Media.Brushes]::DarkSlateGray,
        [double]$Thickness = 0.5
    )
    $line = [System.Windows.Shapes.Line]::new()
    $line.X1 = $X1; $line.X2 = $X2; $line.Y1 = $Y1; $line.Y2 = $Y2
    $line.Stroke = $Brush
    $line.StrokeThickness = $Thickness
    $line.IsHitTestVisible = $false
    $Canvas.Children.Add($line) | Out-Null
}

function Add-HistoricalChartText {
    param(
        [System.Windows.Controls.Canvas]$Canvas,
        [string]$Text,
        [double]$Left, [double]$Top, [double]$Width,
        [System.Windows.TextAlignment]$Alignment = [System.Windows.TextAlignment]::Left,
        [System.Windows.Media.Brush]$Brush = [System.Windows.Media.Brushes]::LightGray
    )
    $label = [System.Windows.Controls.TextBlock]::new()
    $label.Text = $Text
    $label.Foreground = $Brush
    $label.FontSize = 10
    $label.Width = [math]::Max(1.0, $Width)
    $label.TextAlignment = $Alignment
    $label.IsHitTestVisible = $false
    [System.Windows.Controls.Canvas]::SetLeft($label, $Left)
    [System.Windows.Controls.Canvas]::SetTop($label, $Top)
    $Canvas.Children.Add($label) | Out-Null
}

function Get-HistoricalObservationTimestamps {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [AllowEmptyCollection()]
        [object[]]$Observations
    )

    @(
        foreach ($observation in $Observations) {
            $observedAtUtc = $observation.observedAtUtc
            if ($observedAtUtc -is [DateTimeOffset]) {
                $observedAtUtc.ToUniversalTime()
            }
            else {
                [DateTimeOffset]::Parse(
                    [string]$observedAtUtc,
                    [System.Globalization.CultureInfo]::InvariantCulture
                ).ToUniversalTime()
            }
        }
    )
}

function Set-HistoricalChartSeries {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNull()]
        [pscustomobject]$View,

        [Parameter(Mandatory)]
        [ValidateNotNull()]
        [pscustomobject]$Series
    )

    $View.Series = $Series
    $View | Add-Member -NotePropertyName HasInspection -NotePropertyValue $false -Force
    $View.ObservationTimesUtc = @(Get-HistoricalObservationTimestamps `
        -Observations @($Series.observations))
    $View.TitleText.Text = '{0} ({1}){2}' -f $Series.displayName, $Series.symbol, `
        $(if ($Series.isProxy) { " | Proxy for $($Series.proxyFor)" } else { '' })
    $View.SourceText.Text = 'Source: {0}{1}' -f $Series.sourceName, `
        $(if ([string]::IsNullOrWhiteSpace([string]$Series.attribution)) { '' } else { " | $($Series.attribution)" })
    $View.IntervalText.Text = "Interval: $($Series.interval)"
    $View.MeasurementText.Text = "Unit: $($Series.unit)"
    $statusLabel = if ($Series.status -eq 'partial' -and $Series.freshness -eq 'cached') {
        'Partial | Cached'
    }
    else {
        switch ($Series.freshness) {
            'cached' { 'Cached' }
            'delayed' { 'Delayed' }
            'partial' { 'Partial' }
            'unavailable' { 'Unavailable' }
            default { 'Live' }
        }
    }
    $View.StatusText.Text = if ([string]::IsNullOrWhiteSpace([string]$Series.reason)) {
        $statusLabel
    }
    else {
        "$statusLabel | $($Series.reason)"
    }
    $View.StatusText.ToolTip = $View.StatusText.Text
    Update-HistoricalChartPlot -View $View
}

function New-HistoricalChartView {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNull()]
        [pscustomobject]$Series,

        [Parameter()]
        [scriptblock]$OnRangeChanged,

        [Parameter()]
        [scriptblock]$OnRefresh,

        [Parameter()]
        [scriptblock]$OnCancel,

        [Parameter()]
        [object[]]$Instruments,

        [Parameter()]
        [scriptblock]$OnInstrumentChanged
    )

    $xamlPath = Join-Path $PSScriptRoot '..\..\Views\HistoricalChart.xaml'
    $reader = [System.Xml.XmlReader]::Create($xamlPath)
    try {
        $root = [System.Windows.Markup.XamlReader]::Load($reader)
    }
    finally {
        $reader.Dispose()
    }

    $view = [pscustomobject]@{
        Root = $root
        Series = $Series
        ObservationTimesUtc = @(Get-HistoricalObservationTimestamps -Observations @($Series.observations))
        PlotCanvas = $root.FindName('plotCanvas')
        TitleText = $root.FindName('titleText')
        SourceText = $root.FindName('sourceText')
        StatusText = $root.FindName('statusText')
        IntervalText = $root.FindName('intervalText')
        MeasurementText = $root.FindName('measurementText')
        RangeSelector = $root.FindName('rangeSelector')
        CustomRangePanel = $root.FindName('customRangePanel')
        CustomStartDatePicker = $root.FindName('customStartDatePicker')
        CustomEndDatePicker = $root.FindName('customEndDatePicker')
        InstrumentSelector = $root.FindName('instrumentSelector')
        RefreshButton = $root.FindName('refreshButton')
        CancelButton = $root.FindName('cancelButton')
        InspectionText = $root.FindName('inspectionText')
        ZoomInButton = $root.FindName('zoomInButton')
        ZoomOutButton = $root.FindName('zoomOutButton')
        PanLeftButton = $root.FindName('panLeftButton')
        PanRightButton = $root.FindName('panRightButton')
        ResetViewButton = $root.FindName('resetViewButton')
        ZoomFactor = 1.0
        PanOffset = 0.0
        InspectionIndex = 0
    }
    foreach ($range in @('1d', '1w', '1m', '3m', '6m', '1y', '5y', 'custom')) {
        [void]$view.RangeSelector.Items.Add($range)
    }
    $view.RangeSelector.SelectedItem = if ($Series.range -in @('1d', '1w', '1m', '3m', '6m', '1y', '5y', 'custom')) {
        $Series.range
    }
    else {
        '1d'
    }
    $view.RangeSelector.IsEnabled = $null -ne $OnRangeChanged -or $null -ne $OnRefresh
    if (-not $view.RangeSelector.IsEnabled) {
        $view.RangeSelector.ToolTip = 'Range selection is enabled when the history service is connected.'
    }
    $view.CustomStartDatePicker.SelectedDate = [DateTime]::UtcNow.Date.AddDays(-30)
    $view.CustomEndDatePicker.SelectedDate = [DateTime]::UtcNow.Date
    $view.CustomRangePanel.Visibility = if ($view.RangeSelector.SelectedItem -eq 'custom') {
        [System.Windows.Visibility]::Visible
    }
    else {
        [System.Windows.Visibility]::Collapsed
    }
    $view.RefreshButton.IsEnabled = $null -ne $OnRefresh
    $view.CancelButton.IsEnabled = $false
    $instrumentChoices = if (@($Instruments).Count -gt 0 -and $null -ne $OnInstrumentChanged) {
        @($Instruments)
    }
    else {
        @([pscustomobject]@{ instrumentId = $Series.instrumentId; displayName = $Series.displayName; symbol = $Series.symbol })
    }
    foreach ($choice in $instrumentChoices) {
        $instrumentItem = [System.Windows.Controls.ComboBoxItem]::new()
        $sourceLabel = switch (@($choice.sourceIds)[0]) { 'fred' { ' - FRED' } 'ecb-reference-rates' { ' - ECB' } default { '' } }
        $instrumentItem.Content = '{0} ({1}){2}' -f $choice.displayName, $choice.symbol, $sourceLabel
        $instrumentItem.Tag = $choice.instrumentId
        $view.InstrumentSelector.Items.Add($instrumentItem) | Out-Null
        if ($choice.instrumentId -eq $Series.instrumentId) {
            $view.InstrumentSelector.SelectedItem = $instrumentItem
        }
    }
    if ($view.InstrumentSelector.SelectedIndex -lt 0) { $view.InstrumentSelector.SelectedIndex = 0 }
    $view.InstrumentSelector.IsEnabled = $instrumentChoices.Count -gt 1
    $view.InstrumentSelector.ToolTip = if ($view.InstrumentSelector.IsEnabled) {
        'Choose an ECB currency pair or a FRED series (FRED needs a free API key in Settings).'
    }
    else {
        'Only the rights-approved EUR/USD daily ECB series is currently available.'
    }
    Set-HistoricalChartSeries -View $view -Series $Series

    $render = Get-Command Update-HistoricalChartPlot -CommandType Function -ErrorAction Stop
    $inspect = Get-Command Set-HistoricalChartInspection -CommandType Function -ErrorAction Stop
    $plotMargins = Get-HistoricalChartMargins
    $view.ZoomInButton.Add_Click({
            $view.ZoomFactor = [math]::Min(12.0, [double]$view.ZoomFactor * 1.25)
            & $render -View $view
        }.GetNewClosure())
    $view.ZoomOutButton.Add_Click({
            $view.ZoomFactor = [math]::Max(1.0, [double]$view.ZoomFactor / 1.25)
            if ($view.ZoomFactor -le 1.0) { $view.PanOffset = 0.0 }
            & $render -View $view
        }.GetNewClosure())
    $view.PanRightButton.Add_Click({
            $visibleSpan = 1.0 / [math]::Max(1.0, [double]$view.ZoomFactor)
            $view.PanOffset = [math]::Min(1.0 - $visibleSpan, [double]$view.PanOffset + $visibleSpan * 0.1)
            & $render -View $view
        }.GetNewClosure())
    $view.PanLeftButton.Add_Click({
            $visibleSpan = 1.0 / [math]::Max(1.0, [double]$view.ZoomFactor)
            $view.PanOffset = [math]::Max(0.0, [double]$view.PanOffset - $visibleSpan * 0.1)
            & $render -View $view
        }.GetNewClosure())
    $view.ResetViewButton.Add_Click({
            $view.ZoomFactor = 1.0
            $view.PanOffset = 0.0
            & $render -View $view
        }.GetNewClosure())
    if ($view.InstrumentSelector.IsEnabled) {
        $instrumentChanged = $OnInstrumentChanged
        $view.InstrumentSelector.Add_SelectionChanged({
                $selected = $view.InstrumentSelector.SelectedItem
                if ($null -ne $selected -and [string]$selected.Tag -ne [string]$view.Series.instrumentId) {
                    & $instrumentChanged ([string]$selected.Tag)
                }
            }.GetNewClosure())
    }
    $rangeChanged = $OnRangeChanged
    $view.RangeSelector.Add_SelectionChanged({
            $view.CustomRangePanel.Visibility = if ($view.RangeSelector.SelectedItem -eq 'custom') {
                [System.Windows.Visibility]::Visible
            }
            else {
                [System.Windows.Visibility]::Collapsed
            }
            if ($null -ne $rangeChanged) {
                & $rangeChanged ([string]$view.RangeSelector.SelectedItem) ([string]$view.Series.instrumentId)
            }
        }.GetNewClosure())
    if ($null -ne $OnRefresh) {
        $refresh = $OnRefresh
        $view.RefreshButton.Add_Click({
                $range = [string]$view.RangeSelector.SelectedItem
                $customStart = $null
                $customEnd = $null
                if ($range -eq 'custom') {
                    if ($null -eq $view.CustomStartDatePicker.SelectedDate -or
                        $null -eq $view.CustomEndDatePicker.SelectedDate) {
                        $view.StatusText.Text = 'Choose both dates for a custom range.'
                        $view.StatusText.ToolTip = $view.StatusText.Text
                        return
                    }
                    $startDate = [DateTime]$view.CustomStartDatePicker.SelectedDate
                    $endDate = [DateTime]$view.CustomEndDatePicker.SelectedDate
                    $customStart = [DateTimeOffset]::new($startDate.Date, [TimeSpan]::Zero)
                    $customEnd = [DateTimeOffset]::new(
                        $endDate.Date.AddDays(1).AddSeconds(-1),
                        [TimeSpan]::Zero
                    )
                    if ($customStart -ge $customEnd) {
                        $view.StatusText.Text = 'Choose a custom start date earlier than its end date.'
                        $view.StatusText.ToolTip = $view.StatusText.Text
                        return
                    }
                }
                & $refresh $range ([string]$view.Series.instrumentId) $customStart $customEnd
            }.GetNewClosure())
    }
    if ($null -ne $OnCancel) {
        $cancel = $OnCancel
        $view.CancelButton.IsEnabled = $false
        $view.CancelButton.Add_Click({
                & $cancel
            }.GetNewClosure())
    }
    $view.PlotCanvas.Add_SizeChanged({
            & $render -View $view
        }.GetNewClosure())
    $view.PlotCanvas.Add_MouseLeftButtonDown({
            $point = [System.Windows.Input.Mouse]::GetPosition($view.PlotCanvas)
            $plotWidth = [math]::Max(1.0, $view.PlotCanvas.ActualWidth - $plotMargins.Left - $plotMargins.Right)
            $fraction = [math]::Min(1.0, [math]::Max(0.0, ($point.X - $plotMargins.Left) / $plotWidth))
            $visibleSpan = 1.0 / [math]::Max(1.0, [double]$view.ZoomFactor)
            $dataPosition = [double]$view.PanOffset + ($fraction * $visibleSpan)
            $observations = @($view.Series.observations)
            if ($observations.Count -gt 0) {
                $timestamps = @($view.ObservationTimesUtc)
                $firstTicks = $timestamps[0].Ticks
                $lastTicks = $timestamps[-1].Ticks
                $targetTicks = $firstTicks + [long](($lastTicks - $firstTicks) * $dataPosition)
                $nearestIndex = 0
                $nearestDistance = [long]::MaxValue
                for ($index = 0; $index -lt $timestamps.Count; $index++) {
                    $distance = [math]::Abs($timestamps[$index].Ticks - $targetTicks)
                    if ($distance -lt $nearestDistance) {
                        $nearestDistance = $distance
                        $nearestIndex = $index
                    }
                }
                $view.InspectionIndex = $nearestIndex
                $timestamp = $timestamps[$nearestIndex]
                & $inspect -View $view -TimestampUtc $timestamp
                $view.PlotCanvas.Focus() | Out-Null
            }
        }.GetNewClosure())
    $view.PlotCanvas.Add_KeyDown({
            $observations = @($view.Series.observations)
            if ($observations.Count -eq 0) { return }
            if ($_.Key -eq [System.Windows.Input.Key]::Right) {
                $view.InspectionIndex = [math]::Min($observations.Count - 1, $view.InspectionIndex + 1)
            }
            elseif ($_.Key -eq [System.Windows.Input.Key]::Left) {
                $view.InspectionIndex = [math]::Max(0, $view.InspectionIndex - 1)
            }
            else {
                return
            }
            $timestamp = [DateTimeOffset]::Parse(
                [string]$observations[$view.InspectionIndex].observedAtUtc,
                [System.Globalization.CultureInfo]::InvariantCulture
            )
            & $inspect -View $view -TimestampUtc $timestamp
            $_.Handled = $true
        }.GetNewClosure())
    $view
}

function Set-HistoricalChartInspection {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$View,

        [Parameter(Mandatory)]
        [DateTimeOffset]$TimestampUtc
    )

    $timestamp = $TimestampUtc.ToUniversalTime()
    $observation = $View.Series.observations | Where-Object {
        [DateTimeOffset]::Parse(
            [string]$_.observedAtUtc,
            [System.Globalization.CultureInfo]::InvariantCulture
        ).ToUniversalTime() -eq $timestamp
    } | Select-Object -First 1
    if ($null -eq $observation) {
        $View.InspectionText.Text = "No observation exists at $($timestamp.ToString('yyyy-MM-dd HH:mm UTC'))."
        return
    }

    $View.InspectionIndex = [array]::IndexOf(@($View.Series.observations), $observation)
    $inspectionTimestamp = if ($observation.timestampPrecision -eq 'date') {
        '{0} UTC date anchor (publication time unavailable)' -f $timestamp.ToString('yyyy-MM-dd')
    }
    else {
        $timestamp.ToString('yyyy-MM-dd HH:mm UTC')
    }
    $View.InspectionText.Text = '{0} | {1} {2}' -f `
        $inspectionTimestamp, $observation.value, $View.Series.unit
    $View | Add-Member -NotePropertyName HasInspection -NotePropertyValue $true -Force
    Update-HistoricalChartPlot -View $View
}