fix the pause function.
the timer does pause but the pasue text does not dissapear after a resume

<#
.SYNOPSIS
    An interactive, persistent, and highly configurable productivity timer.
.DESCRIPTION
    A flicker-free console timer with advanced features, refactored into a modular,
    class-based architecture for improved readability and maintainability.
    - Configurable interval duration, beep sound, and beep count via parameters.
    - Interactive controls: Pause/Resume (P) and Skip (S).
    - Persistent State: Autosaves after each interval and prompts to load on startup.
.PARAMETER IntervalSeconds
    The duration of each work interval in seconds. Default is 600 (10 minutes).
.PARAMETER BeepVolumeScale
    Sets the beep pitch on a scale of 1 (low) to 10 (high). Default is 5.
.PARAMETER BeepCount
    The number of times to beep at the end of an interval. Max is 10. Default is 3.
.USAGE
    # Run with defaults (10 min interval, medium beep, 3 beeps)
    .\StudyClock_Refactored.ps1

    # Run a 30-minute interval with a loud, single beep
    .\StudyClock_Refactored.ps1 -IntervalSeconds 1800 -BeepVolumeScale 8 -BeepCount 1
#>

#================================================================================
# --- Script Parameters ---
#================================================================================
param(
    [Parameter(HelpMessage = "The duration of each work interval in seconds.")]
    [int]$IntervalSeconds = 600,

    [Parameter(HelpMessage = "Sets the beep pitch on a scale of 1 (low) to 10 (high).")]
    [ValidateRange(1, 10)]
    [int]$BeepVolumeScale = 5,

    [Parameter(HelpMessage = "The number of times to beep at the end of an interval.")]
    [ValidateRange(1, 10)]
    [int]$BeepCount = 3
)

#================================================================================
# --- Class Definitions ---
#================================================================================

#region Classes

# Represents the script's configuration settings.
class StudyClockConfiguration {
    [int]$IntervalSeconds
    [int]$BeepVolumeScale
    [int]$BeepCount
    [int]$BeepDurationMs = 250
    [int]$BeepPauseMs = 250
    [string]$StateFilePath = ".\studyclock.state.json"

    StudyClockConfiguration([int]$Interval, [int]$Volume, [int]$Beeps) {
        $this.IntervalSeconds = $Interval
        $this.BeepVolumeScale = $Volume
        $this.BeepCount = $Beeps
    }
}

# Represents a single completed interval for tracking.
class IntervalRecord {
    [int]$Number
    [string]$StartTime
    [int]$IntendedDurationSeconds

    IntervalRecord([int]$Num, [datetime]$Start, [int]$Duration) {
        $this.Number = $Num
        $this.StartTime = $Start.ToString('HH:mm')
        $this.IntendedDurationSeconds = $Duration
    }
}

# Manages the application's persistent state (completed intervals).
class TimerState {
    [System.Collections.Generic.List[IntervalRecord]]$CompletedIntervals
    [int]$IntervalCounter

    TimerState() {
        $this.CompletedIntervals = [System.Collections.Generic.List[IntervalRecord]]::new()
        $this.IntervalCounter = 1
    }

    # Adds a new completed interval and increments the counter.
    AddCompletedInterval([datetime]$StartTime, [int]$Duration) {
        $record = [IntervalRecord]::new($this.IntervalCounter, $StartTime, $Duration)
        $this.CompletedIntervals.Add($record)
        $this.IntervalCounter++
    }

    # Saves the current state to a JSON file.
    Save([string]$Path) {
        $this | ConvertTo-Json -Depth 5 | Set-Content -Path $Path
    }

    # Static method to load state from a file or create a new one.
    static [TimerState] Load([string]$Path) {
        if (-not (Test-Path $Path)) {
            return [TimerState]::new()
        }

        $response = Read-Host "Load previous session? (Y/n)"
        if ($response -match '^[nN]') { # Made the check case-insensitive
            return [TimerState]::new()
        }

        try {
            $jsonData = Get-Content -Path $Path | ConvertFrom-Json
            $state = [TimerState]::new()
            $state.IntervalCounter = $jsonData.IntervalCounter
            
            # Re-hydrate the generic list with strongly-typed IntervalRecord objects
            # Check if CompletedIntervals exists and is not null before iterating
            if ($null -ne $jsonData.CompletedIntervals) {
                foreach ($item in $jsonData.CompletedIntervals) {
                    # The StartTime is saved as a string, so we need to parse it back to a datetime
                    # to create a valid IntervalRecord object. This was a subtle bug in the previous version.
                    $startTimeAsDateTime = [datetime]::ParseExact($item.StartTime, 'HH:mm', $null)

                    $record = [IntervalRecord]::new(
                        $item.Number,
                        $startTimeAsDateTime,
                        $item.IntendedDurationSeconds
                    )
                    $state.CompletedIntervals.Add($record)
                }
            }
            return $state
        }
        catch {
            Write-Warning "Could not load or parse state file. Starting new session."
            return [TimerState]::new()
        }
    }
}

# Manages all console input and output (UI).
class StudyClockUI {
    # Private members for ANSI escape codes
    hidden [string]$esc = [char]27
    hidden [string]$cursorHome = "$($this.esc)[H"
    hidden [string]$colorYellow = "$($this.esc)[93m"
    hidden [string]$colorGreen = "$($this.esc)[32m"
    hidden [string]$colorCyan = "$($this.esc)[36m"
    hidden [string]$colorRed = "$($this.esc)[91m"
    hidden [string]$colorReset = "$($this.esc)[0m"

    # Prepares the console for the application.
    Setup() {
        [System.Console]::CursorVisible = $false
        Clear-Host
    }

    # Restores the console to its original state.
    Cleanup() {
        [System.Console]::CursorVisible = $true
    }

    # Renders the entire UI frame.
    Render([hashtable]$UIData) {
        $sb = [System.Text.StringBuilder]::new()

        # 1. Build the dynamic Info Header
        $intervalInfo = "Interval: $($UIData.IntervalSeconds)s"
        if ($UIData.IntervalSeconds -eq 600) { $intervalInfo += " (default)" }

        $volumeInfo = "Volume: $($UIData.BeepVolumeScale)"
        if ($UIData.BeepVolumeScale -eq 5) { $volumeInfo += " (default)" }

        $countInfo = "Beeps: $($UIData.BeepCount)"
        if ($UIData.BeepCount -eq 3) { $countInfo += " (default)" }

        [void]$sb.AppendLine("$($this.colorYellow)$intervalInfo | $volumeInfo | $countInfo$($this.colorReset)")
        [void]$sb.AppendLine()

        # 2. Build the completed intervals list
        [void]$sb.AppendLine("$($this.colorYellow)#n [Start]   [Progress] [Current]$($this.colorReset)")
        [void]$sb.AppendLine("$($this.colorYellow)---------------------------------------$($this.colorReset)")

        foreach ($interval in $UIData.CompletedIntervals) {
            $totalMinutes = [math]::Round($interval.IntendedDurationSeconds / 60)
            $line = "#$($interval.Number)".PadRight(3) + " $($interval.StartTime)   ($totalMinutes/$totalMinutes)"
            [void]$sb.AppendLine("$($this.colorGreen)$line$($this.colorReset)")
        }

        # 3. Build the current interval line
        $elapsed = $UIData.LiveTimestamp - $UIData.CurrentIntervalStartTime
        $totalMinutes = [math]::Round($UIData.IntervalSeconds / 60)
        $minutesPassed = [math]::Floor($elapsed.TotalMinutes)
        $startString = $UIData.CurrentIntervalStartTime.ToString('HH:mm')
        $progressString = "($minutesPassed/$totalMinutes)".PadRight(10)
        $currentString = $UIData.LiveTimestamp.ToString('HH:mm:ss.f')
        $currentLine = "#$($UIData.CurrentIntervalNumber)".PadRight(3) + " $startString   $progressString $currentString"

        if ($UIData.IsPaused) {
            $currentLine += "  $($this.colorRed)-- PAUSED --$($this.colorReset)"
        }

        [void]$sb.AppendLine("$($this.colorCyan)$currentLine$($this.colorReset)")
        [void]$sb.AppendLine()
        [void]$sb.AppendLine("Controls: [P] Pause/Resume | [S] Skip Interval | [Ctrl+C] Exit")

        Write-Host -NoNewline ($this.cursorHome + $sb.ToString())
    }
    
    # Displays a message between intervals.
    DisplayIntervalComplete() {
        Clear-Host
    }
}

# The main application engine, orchestrating all other components.
class TimerEngine {
    [StudyClockConfiguration]$Configuration
    [TimerState]$State
    [StudyClockUI]$UI

    TimerEngine([StudyClockConfiguration]$Config) {
        $this.Configuration = $Config
        $this.UI = [StudyClockUI]::new()
        $this.State = [TimerState]::Load($this.Configuration.StateFilePath)
    }

    # The main application entry point.
    Start() {
        $this.UI.Setup()
        try {
            while ($true) {
                $this.RunInterval()
            }
        }
        finally {
            $this.UI.Cleanup()
        }
    }

    # Private helper to run a single interval loop.
    hidden RunInterval() {
        # Mark the wall-clock start (for display & record keeping)
        $intervalStartTime = Get-Date

        # Use a Stopwatch to track elapsed, so Stop()/Start() pauses it cleanly
        $stopwatch = [System.Diagnostics.Stopwatch]::StartNew()

        $isPaused     = $false
        $skipInterval = $false

        while ($stopwatch.Elapsed.TotalSeconds -lt $this.Configuration.IntervalSeconds) {

            # ---- Handle Keys ----
            if ([Console]::KeyAvailable) {
                $key = [Console]::ReadKey($true)
                switch ($key.Key) {
                    'P' {
                        if ($stopwatch.IsRunning) {
                            $stopwatch.Stop()
                            $isPaused = $true
                        }
                        else {
                            $stopwatch.Start()
                            $isPaused = $false
                        }
                    }
                    'S' { 
                        $skipInterval = $true 
                    }
                }
            }
            if ($skipInterval) { break }

            # ---- Build data for UI ----
            # derive a "virtual" current clock by adding elapsed to start
            $liveTimestamp = $intervalStartTime.Add($stopwatch.Elapsed)

            $renderData = @{
                CompletedIntervals       = $this.State.CompletedIntervals
                CurrentIntervalNumber    = $this.State.IntervalCounter
                CurrentIntervalStartTime = $intervalStartTime
                LiveTimestamp            = $liveTimestamp
                IsPaused                 = $isPaused
                IntervalSeconds          = $this.Configuration.IntervalSeconds
                BeepVolumeScale          = $this.Configuration.BeepVolumeScale
                BeepCount                = $this.Configuration.BeepCount
            }

            $this.UI.Render($renderData)

            Start-Sleep -Milliseconds 100
        }

        # ---- Interval Complete ----
        $this.InvokeBeep()
        $this.State.AddCompletedInterval($intervalStartTime, $this.Configuration.IntervalSeconds)
        $this.State.Save($this.Configuration.StateFilePath)
        $this.UI.DisplayIntervalComplete()
    }

    # Private helper for beeping.
    hidden InvokeBeep() {
        $minHz = 500; $maxHz = 1500
        $frequency = [int]($minHz + (($this.Configuration.BeepVolumeScale - 1) / 9.0) * ($maxHz - $minHz))

        for ($i = 0; $i -lt $this.Configuration.BeepCount; $i++) {
            [System.Console]::Beep($frequency, $this.Configuration.BeepDurationMs)
            if ($i -lt ($this.Configuration.BeepCount - 1)) {
                Start-Sleep -Milliseconds $this.Configuration.BeepPauseMs
            }
        }
    }
}

#endregion Classes

#================================================================================
# --- Main Application Execution ---
#================================================================================

# 1. Create a configuration object from the script parameters.
$config = [StudyClockConfiguration]::new($IntervalSeconds, $BeepVolumeScale, $BeepCount)

# 2. Create the main engine with the specified configuration.
$timer = [TimerEngine]::new($config)

# 3. Start the timer. The engine's try/finally block handles cleanup.
$timer.Start()