<#
    BenchKit - Windows Tech Toolkit  v1.0.0
    ------------------------------------------------------------------
    Repair, cleanup, network and security fixes, smart diagnostics,
    a live system monitor, automation profiles, a work log and
    customer-ready HTML reports - in one window.

    Run:   double-click BenchKit.cmd
     or:   powershell -NoProfile -ExecutionPolicy Bypass -File .\BenchKit.ps1

    Needs Windows 10/11 and administrator rights (it asks for them).
    Every task shows the exact commands it will run before it runs.
    Data (settings, profiles, logs, reports): %ProgramData%\Cybrac BenchKit
#>

#region ---- Elevation and host check -------------------------------------------------------
$IsAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
    [Security.Principal.WindowsBuiltInRole]::Administrator)

if (-not $IsAdmin -or $PSVersionTable.PSEdition -eq 'Core') {
    # Always run in Windows PowerShell 5.1 (needed for Checkpoint-Computer) and elevated.
    $winPS   = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
    $argLine = "-NoProfile -ExecutionPolicy Bypass -STA -File `"$PSCommandPath`""
    try {
        if ($IsAdmin) { Start-Process -FilePath $winPS -ArgumentList $argLine }
        else          { Start-Process -FilePath $winPS -ArgumentList $argLine -Verb RunAs }
    } catch {
        Write-Host 'BenchKit needs administrator rights to run.' -ForegroundColor Red
        Start-Sleep -Seconds 4
    }
    exit
}
#endregion

Add-Type -AssemblyName System.Windows.Forms, System.Drawing, Microsoft.VisualBasic
[System.Windows.Forms.Application]::EnableVisualStyles()

#region ---- Launch passcode gate -----------------------------------------------------------
# A shop passcode so a copy left on (or taken from) a customer PC can't just be run by anyone.
# This is a DETERRENT, not strong security - the script is readable text. The real protection is
# not leaving the tool/secrets on customer machines (and the server-gated download, planned).
# Stored as a SHA-256 hash, never the plaintext. Blank = no prompt. Use "Set launch passcode" in
# Settings to generate a new hash to paste on the line below. Default code: 1422
$LaunchPassHash = 'fd53efd8940f305f79e212dc2e0a557d23eab8f2f60fbf219e19e3351b68e732'
function Get-TextSha256([string]$Text) {
    $sha = [System.Security.Cryptography.SHA256]::Create()
    return ([System.BitConverter]::ToString($sha.ComputeHash([System.Text.Encoding]::UTF8.GetBytes([string]$Text))).Replace('-', '').ToLower())
}
function Test-LaunchPass {
    if (-not $LaunchPassHash) { return $true }
    for ($try = 1; $try -le 3; $try++) {
        $f = New-Object System.Windows.Forms.Form
        $f.Text = 'BenchKit'; $f.FormBorderStyle = 'FixedDialog'; $f.StartPosition = 'CenterScreen'
        $f.MaximizeBox = $false; $f.MinimizeBox = $false; $f.ShowInTaskbar = $true; $f.ClientSize = New-Object System.Drawing.Size(330, 128)
        $f.Font = New-Object System.Drawing.Font('Segoe UI', 9)
        $lbl = New-Object System.Windows.Forms.Label
        $lbl.Text = $(if ($try -gt 1) { 'Incorrect passcode. Try again:' } else { 'Enter the BenchKit passcode to continue:' })
        $lbl.SetBounds(14, 14, 302, 20)
        $tb = New-Object System.Windows.Forms.TextBox; $tb.UseSystemPasswordChar = $true; $tb.SetBounds(14, 40, 302, 24)
        $ok = New-Object System.Windows.Forms.Button; $ok.Text = 'OK'; $ok.DialogResult = 'OK'; $ok.SetBounds(158, 82, 74, 30)
        $cancel = New-Object System.Windows.Forms.Button; $cancel.Text = 'Cancel'; $cancel.DialogResult = 'Cancel'; $cancel.SetBounds(242, 82, 74, 30)
        $f.Controls.AddRange(@($lbl, $tb, $ok, $cancel)); $f.AcceptButton = $ok; $f.CancelButton = $cancel
        $r = $f.ShowDialog(); $val = $tb.Text; $f.Dispose()
        if ($r -ne [System.Windows.Forms.DialogResult]::OK) { return $false }
        if ((Get-TextSha256 $val) -eq $LaunchPassHash.ToLower()) { return $true }
    }
    return $false
}
if (-not (Test-LaunchPass)) { exit }
function Read-Secret([string]$Title, [string]$Prompt) {
    $f = New-Object System.Windows.Forms.Form
    $f.Text = $Title; $f.FormBorderStyle = 'FixedDialog'; $f.StartPosition = 'CenterParent'; $f.MaximizeBox = $false; $f.MinimizeBox = $false; $f.ShowInTaskbar = $false
    $f.ClientSize = New-Object System.Drawing.Size(360, 128); $f.Font = New-Object System.Drawing.Font('Segoe UI', 9)
    $lbl = New-Object System.Windows.Forms.Label; $lbl.Text = $Prompt; $lbl.SetBounds(14, 14, 332, 20)
    $tb = New-Object System.Windows.Forms.TextBox; $tb.UseSystemPasswordChar = $true; $tb.SetBounds(14, 40, 332, 24)
    $ok = New-Object System.Windows.Forms.Button; $ok.Text = 'OK'; $ok.DialogResult = 'OK'; $ok.SetBounds(188, 82, 74, 30)
    $cancel = New-Object System.Windows.Forms.Button; $cancel.Text = 'Cancel'; $cancel.DialogResult = 'Cancel'; $cancel.SetBounds(272, 82, 74, 30)
    $f.Controls.AddRange(@($lbl, $tb, $ok, $cancel)); $f.AcceptButton = $ok; $f.CancelButton = $cancel
    $r = $f.ShowDialog(); $v = $tb.Text; $f.Dispose()
    if ($r -ne [System.Windows.Forms.DialogResult]::OK) { return $null }
    return $v
}
#endregion

#region ---- Paths, settings, profiles -------------------------------------------------------
$AppName      = 'BenchKit'
$AppVersion   = '1.0.0'
# Data lives in a Cybrac-branded folder (C:\ProgramData\Cybrac BenchKit) for brand recognition.
$DataDir      = Join-Path $env:ProgramData 'Cybrac BenchKit'
$LogDir       = Join-Path $DataDir 'Logs'
$ReportDir    = Join-Path $DataDir 'Reports'
$SettingsFile = Join-Path $DataDir 'settings.json'
$ProfilesFile = Join-Path $DataDir 'profiles.json'
$RecoveryDir  = Join-Path $DataDir 'Recovery'
$ToolboxDir   = Join-Path $DataDir 'Toolbox'
$ToolboxFile  = Join-Path $DataDir 'toolbox.json'

# One-time move of data from older locations so existing settings, profiles, logs and
# reports carry over to the new Cybrac BenchKit folder.
foreach ($old in @((Join-Path $env:ProgramData 'BenchKit'), (Join-Path (Join-Path $env:ProgramData 'Cybrac') 'BenchKit'))) {
    if ((Test-Path -LiteralPath $old) -and -not (Test-Path -LiteralPath $DataDir)) {
        try { Move-Item -LiteralPath $old -Destination $DataDir -Force -ErrorAction Stop } catch { }
    }
}

function Initialize-DataDirs {
    foreach ($d in $DataDir, $LogDir, $ReportDir, $RecoveryDir, $ToolboxDir) {
        if (-not (Test-Path -LiteralPath $d)) { New-Item -ItemType Directory -Path $d -Force | Out-Null }
    }
}
Initialize-DataDirs
$LogFile = Join-Path $LogDir ('session-{0:yyyyMMdd-HHmmss}.log' -f (Get-Date))

$DefaultSettings = [ordered]@{
    Theme           = 'Light'
    CompanyName     = 'Cybrac.com'
    CompanyPhone    = '712-476-5004'
    CompanyWebsite  = 'https://cybrac.com/'
    TechName        = 'Tech 1'
    ConfirmCommands = $true
    Tools           = @()
    RemoteInstaller = ''
    RemoteArgs      = '/qn'
    RemoteLaunchExe = ''
    PcrtFolder      = ''
    FabPath         = ''
    Msp360Path      = ''
    LogoPath        = ''
    TrackerUrl      = 'https://cybrac.me/ticket/repair/report-upload.php'
    AttachUrl       = 'https://cybrac.me/ticket/repair/benchkit_attach.php'
    StoreHash       = ''
}

function Get-Settings {
    $s = [ordered]@{}
    foreach ($k in $DefaultSettings.Keys) { $s[$k] = $DefaultSettings[$k] }
    if (Test-Path -LiteralPath $SettingsFile) {
        try {
            $j = Get-Content -LiteralPath $SettingsFile -Raw | ConvertFrom-Json
            foreach ($p in $j.PSObject.Properties) { $s[$p.Name] = $p.Value }
        } catch { }
    }
    $s['Tools'] = @($s['Tools'] | Where-Object { $_ })
    return $s
}

function Save-Settings {
    Initialize-DataDirs
    $script:Settings | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $SettingsFile -Encoding UTF8
}

function Get-CustomProfiles {
    $h = [ordered]@{}
    if (Test-Path -LiteralPath $ProfilesFile) {
        try {
            $j = Get-Content -LiteralPath $ProfilesFile -Raw | ConvertFrom-Json
            foreach ($p in $j.PSObject.Properties) { $h[$p.Name] = @($p.Value) }
        } catch { }
    }
    return $h
}

function Save-CustomProfiles([System.Collections.IDictionary]$Profiles) {
    Initialize-DataDirs
    ($Profiles | ConvertTo-Json -Depth 4) | Set-Content -LiteralPath $ProfilesFile -Encoding UTF8
}

$Settings = Get-Settings

# Curated catalogue of reputable, free portable repair tools, fetched on demand (like Windows Repair Toolbox).
# Kind 'file' = download straight to the Toolbox cache (zip is auto-extracted); 'page' = open the vendor's own
# download page (used where there is no stable direct link, so we never pull from an untrusted mirror).
# URLs drift over time - "Edit list" writes this to toolbox.json where you can correct a URL or add your own tools.
$ToolboxDefault = @(
    @{ Name = 'Malwarebytes Free';      Category = 'Malware removal';       Kind = 'page'; Url = 'https://www.malwarebytes.com/mwb-download' }
    @{ Name = 'AdwCleaner';             Category = 'Malware removal';       Kind = 'file'; Url = 'https://adwcleaner.malwarebytes.com/adwcleaner?channel=release'; File = 'AdwCleaner.exe' }
    @{ Name = 'Emsisoft Emergency Kit'; Category = 'Malware removal';       Kind = 'file'; Url = 'https://dl.emsisoft.com/EmsisoftEmergencyKit.exe'; File = 'EmsisoftEmergencyKit.exe' }
    @{ Name = 'ESET Online Scanner';    Category = 'Malware removal';       Kind = 'file'; Url = 'https://download.eset.com/com/eset/tools/online_scanner/latest/esetonlinescanner.exe'; File = 'esetonlinescanner.exe' }
    @{ Name = 'Kaspersky KVRT';         Category = 'Malware removal';       Kind = 'file'; Url = 'https://devbuilds.s.kaspersky-labs.com/devbuilds/KVRT/latest/full/KVRT.exe'; File = 'KVRT.exe' }
    @{ Name = 'TDSSKiller (rootkits)';  Category = 'Malware removal';       Kind = 'file'; Url = 'https://media.kaspersky.com/utilities/VirusUtilities/EN/tdsskiller.exe'; File = 'tdsskiller.exe' }
    @{ Name = 'SUPERAntiSpyware';       Category = 'Malware removal';       Kind = 'page'; Url = 'https://www.superantispyware.com/' }
    @{ Name = 'Autoruns';               Category = 'Sysinternals';          Kind = 'file'; Url = 'https://download.sysinternals.com/files/Autoruns.zip'; File = 'Autoruns.zip'; Exe = 'Autoruns64.exe' }
    @{ Name = 'Process Explorer';       Category = 'Sysinternals';          Kind = 'file'; Url = 'https://download.sysinternals.com/files/ProcessExplorer.zip'; File = 'ProcessExplorer.zip'; Exe = 'procexp64.exe' }
    @{ Name = 'TCPView';                Category = 'Sysinternals';          Kind = 'file'; Url = 'https://download.sysinternals.com/files/TCPView.zip'; File = 'TCPView.zip'; Exe = 'tcpview64.exe' }
    @{ Name = 'Sysinternals Suite';     Category = 'Sysinternals';          Kind = 'file'; Url = 'https://download.sysinternals.com/files/SysinternalsSuite.zip'; File = 'SysinternalsSuite.zip' }
    @{ Name = 'CrystalDiskInfo';        Category = 'Hardware & diagnostics'; Kind = 'page'; Url = 'https://crystalmark.info/en/software/crystaldiskinfo/' }
    @{ Name = 'HWiNFO';                 Category = 'Hardware & diagnostics'; Kind = 'page'; Url = 'https://www.hwinfo.com/download/' }
    @{ Name = 'CPU-Z';                  Category = 'Hardware & diagnostics'; Kind = 'page'; Url = 'https://www.cpuid.com/softwares/cpu-z.html' }
    @{ Name = 'GPU-Z';                  Category = 'Hardware & diagnostics'; Kind = 'page'; Url = 'https://www.techpowerup.com/gpuz/' }
    @{ Name = 'HWMonitor';              Category = 'Hardware & diagnostics'; Kind = 'page'; Url = 'https://www.cpuid.com/softwares/hwmonitor.html' }
    @{ Name = 'MemTest86';              Category = 'Hardware & diagnostics'; Kind = 'page'; Url = 'https://www.memtest86.com/download.htm' }
    @{ Name = 'FurMark';                Category = 'Hardware & diagnostics'; Kind = 'page'; Url = 'https://geeks3d.com/furmark/' }
    @{ Name = 'CrystalDiskMark';        Category = 'Disk & data';           Kind = 'page'; Url = 'https://crystalmark.info/en/software/crystaldiskmark/' }
    @{ Name = 'TestDisk / PhotoRec';    Category = 'Disk & data';           Kind = 'page'; Url = 'https://www.cgsecurity.org/wiki/TestDisk_Download' }
    @{ Name = 'Recuva';                 Category = 'Disk & data';           Kind = 'page'; Url = 'https://www.ccleaner.com/recuva/download' }
    @{ Name = 'WizTree';                Category = 'Disk & data';           Kind = 'page'; Url = 'https://diskanalyzer.com/download' }
    @{ Name = 'WinDirStat (portable)';  Category = 'Disk & data';           Kind = 'file'; Url = 'https://github.com/windirstat/windirstat/releases/latest/download/WinDirStat.zip'; File = 'WinDirStat.zip'; Exe = 'WinDirStat.exe' }
    @{ Name = 'BleachBit';              Category = 'Disk & data';           Kind = 'page'; Url = 'https://www.bleachbit.org/download' }
    @{ Name = 'Rufus (bootable USB)';   Category = 'Bootable media';        Kind = 'page'; Url = 'https://rufus.ie/' }
    @{ Name = 'Ventoy';                 Category = 'Bootable media';        Kind = 'page'; Url = 'https://www.ventoy.net/en/download.html' }
    # NirSoft diagnostic utilities (nirsoft.net). Note: NirSoft tools often trip antivirus false positives - that is expected.
    # Password-recovery tools (WirelessKeyView, WebBrowserPassView, Mail PassView, etc.) are intentionally NOT listed here;
    # add them yourself via "Edit list" if your workflow needs them.
    @{ Name = 'BlueScreenView';         Category = 'NirSoft (diagnostics)'; Kind = 'file'; Url = 'https://www.nirsoft.net/utils/bluescreenview-x64.zip'; File = 'bluescreenview-x64.zip'; Exe = 'BlueScreenView.exe' }
    @{ Name = 'WhatInStartup';          Category = 'NirSoft (diagnostics)'; Kind = 'file'; Url = 'https://www.nirsoft.net/utils/whatinstartup-x64.zip'; File = 'whatinstartup-x64.zip'; Exe = 'WhatInStartup.exe' }
    @{ Name = 'USBDeview';              Category = 'NirSoft (diagnostics)'; Kind = 'file'; Url = 'https://www.nirsoft.net/utils/usbdeview-x64.zip'; File = 'usbdeview-x64.zip'; Exe = 'USBDeview.exe' }
    @{ Name = 'CurrPorts';              Category = 'NirSoft (diagnostics)'; Kind = 'file'; Url = 'https://www.nirsoft.net/utils/cports-x64.zip'; File = 'cports-x64.zip'; Exe = 'cports.exe' }
    @{ Name = 'NirCmd';                 Category = 'NirSoft (diagnostics)'; Kind = 'file'; Url = 'https://www.nirsoft.net/utils/nircmd-x64.zip'; File = 'nircmd-x64.zip'; Exe = 'nircmd.exe' }
    @{ Name = 'More NirSoft tools';     Category = 'NirSoft (diagnostics)'; Kind = 'page'; Url = 'https://www.nirsoft.net/utils/index.html' }
)
function Get-Toolbox {
    $items = @()
    foreach ($d in $ToolboxDefault) { $items += , ([pscustomobject]$d) }
    if (Test-Path -LiteralPath $ToolboxFile) {
        try {
            $over = Get-Content -LiteralPath $ToolboxFile -Raw | ConvertFrom-Json
            foreach ($o in @($over)) {
                if (-not $o.Name) { continue }
                $ex = $items | Where-Object { $_.Name -eq $o.Name } | Select-Object -First 1
                if ($ex) { foreach ($p in $o.PSObject.Properties) { $ex.$($p.Name) = $p.Value } }
                else { $items += , $o }
            }
        } catch { }
    }
    return $items
}
#endregion

#region ---- Shared state between the window and background tasks ----------------------------
$Sync = [hashtable]::Synchronized(@{
    Queue        = New-Object 'System.Collections.Concurrent.ConcurrentQueue[string]'
    Busy         = $false
    Cancel       = $false
    Status       = 'Ready'
    Progress     = 0
    Total        = 0
    RebootNeeded = $false
    Findings     = $null
    ReportPath   = $null
    Profiles     = @()
    BackupRecord = [System.Collections.ArrayList]::Synchronized((New-Object System.Collections.ArrayList))
    SpeedTests   = [System.Collections.ArrayList]::Synchronized((New-Object System.Collections.ArrayList))
    WorkDone     = [System.Collections.ArrayList]::Synchronized((New-Object System.Collections.ArrayList))
    AppsUpdated  = [System.Collections.ArrayList]::Synchronized((New-Object System.Collections.ArrayList))
})
#endregion

#region ---- Code available to every background task -----------------------------------------
$Common = @'
$ErrorActionPreference = 'Continue'
$ProgressPreference    = 'SilentlyContinue'

function Write-Log {
    param([string]$Message, [string]$Level = 'INFO')
    if ($Level -eq 'WARN' -or $Level -eq 'ERROR') { $global:StepWarn = $true }
    $Sync.Queue.Enqueue(('{0} [{1}] {2}' -f (Get-Date -Format 'HH:mm:ss'), $Level, $Message))
}

# Progress updates (percent lines) are shown as a single, live-updating line in the console.
function Write-Prog([string]$Message) { $Sync.Queue.Enqueue('@@BKPROGRESS@@' + $Message) }

function Emit-ExeToken([string]$line) {
    $line = $line.Trim()
    if (-not $line) { return }
    if ($line -match '\d{1,3}(?:\.\d+)?\s*%') {
        # percent/progress line (e.g. DISM bar, SFC "Verification 12% complete") - show live, in place
        Write-Prog $line
        $Sync.Status = ($line -replace '[\[\]=]', ' ').Trim()
    } elseif ($line.Length -ge 2) {
        $global:LastExeOutput.Add($line)
        Write-Log $line 'OUT'
    }
}

function Invoke-Exe {
    param([string]$File, [string[]]$Arguments = @())
    Write-Log ('> {0} {1}' -f $File, ($Arguments -join ' ')) 'CMD'
    $global:LastExeOutput = New-Object System.Collections.Generic.List[string]
    try {
        $psi = New-Object System.Diagnostics.ProcessStartInfo
        $psi.FileName = $File
        $psi.Arguments = ($Arguments -join ' ')
        $psi.UseShellExecute = $false
        $psi.RedirectStandardOutput = $true
        $psi.RedirectStandardError = $true
        $psi.CreateNoWindow = $true
        $p = [System.Diagnostics.Process]::Start($psi)
    } catch {
        Write-Log ('Could not start {0}: {1}' -f $File, $_.Exception.Message) 'ERROR'
        return -1
    }
    # Read stdout character-by-character so carriage-return progress updates stream live.
    $reader = $p.StandardOutput
    $buf = New-Object char[] 2048
    $tok = New-Object System.Text.StringBuilder
    while (-not $reader.EndOfStream) {
        $read = $reader.Read($buf, 0, $buf.Length)
        if ($read -le 0) { continue }
        for ($i = 0; $i -lt $read; $i++) {
            $ch = $buf[$i]
            if ($ch -eq [char]13 -or $ch -eq [char]10) { Emit-ExeToken ($tok.ToString()); [void]$tok.Clear() }
            else { [void]$tok.Append($ch) }
        }
    }
    if ($tok.Length -gt 0) { Emit-ExeToken ($tok.ToString()) }
    $errtext = ''
    try { $errtext = $p.StandardError.ReadToEnd() } catch { }
    $p.WaitForExit()
    $code = $p.ExitCode
    if ($errtext) { foreach ($el in ($errtext -split "`r?`n")) { if ($el.Trim().Length -ge 2) { Write-Log $el.Trim() 'WARN' } } }
    if ($code -ne 0) { Write-Log ('Exit code: {0}' -f $code) 'WARN' } else { Write-Log 'Exit code: 0' 'CMD' }
    return $code
}

function Get-SizeMB([string]$Path) {
    if (-not (Test-Path -LiteralPath $Path)) { return 0 }
    $sum = (Get-ChildItem -LiteralPath $Path -Recurse -Force -ErrorAction SilentlyContinue |
            Where-Object { -not $_.PSIsContainer } | Measure-Object -Property Length -Sum).Sum
    if (-not $sum) { return 0 }
    return [math]::Round($sum / 1MB, 1)
}

function Clear-Folder {
    param([string]$Path, [string]$Label)
    $targets = @(Resolve-Path -Path $Path -ErrorAction SilentlyContinue | ForEach-Object { $_.ProviderPath })
    if ($targets.Count -eq 0) { Write-Log ('{0}: nothing to clean (folder not found).' -f $Label); return }
    $freed = 0
    foreach ($t in $targets) {
        $before = Get-SizeMB $t
        Get-ChildItem -LiteralPath $t -Force -ErrorAction SilentlyContinue |
            Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
        $freed += ($before - (Get-SizeMB $t))
    }
    Write-Log ('{0}: freed {1:N1} MB (files in use were skipped).' -f $Label, $freed) 'OK'
}

function Stop-Svc([string[]]$Names) {
    foreach ($n in $Names) {
        $s = Get-Service -Name $n -ErrorAction SilentlyContinue
        if ($s -and $s.Status -ne 'Stopped') {
            Write-Log ('Stopping service {0}...' -f $n)
            Stop-Service -Name $n -Force -ErrorAction SilentlyContinue
            try { $s.WaitForStatus('Stopped', '00:00:30') } catch { Write-Log ('{0} did not stop in time.' -f $n) 'WARN' }
        }
    }
}

function Start-Svc([string[]]$Names) {
    foreach ($n in $Names) {
        $s = Get-Service -Name $n -ErrorAction SilentlyContinue
        if ($s -and $s.StartType -ne 'Disabled') {
            Start-Service -Name $n -ErrorAction SilentlyContinue
            Write-Log ('Service {0}: {1}' -f $n, (Get-Service -Name $n).Status)
        }
    }
}

function Get-WingetPath {
    $c = Get-Command winget.exe -ErrorAction SilentlyContinue
    if ($c) { return $c.Source }
    $p = Get-ChildItem "$env:ProgramFiles\WindowsApps\Microsoft.DesktopAppInstaller_*_x64__8wekyb3d8bbwe\winget.exe" -ErrorAction SilentlyContinue |
         Sort-Object FullName -Descending | Select-Object -First 1
    if ($p) { return $p.FullName }
    return $null
}
function Norm-Url([string]$u) {
    $u = ([string]$u).Trim()
    if (-not $u) { return '' }
    if ($u -notmatch '^(?i)https?://') { $u = 'https://' + $u }
    return $u
}
function Web-Link([string]$u) {
    $full = Norm-Url $u
    if (-not $full) { return '' }
    $disp = ($full -replace '^(?i)https?://', '') -replace '/$', ''
    return ('<a href="{0}">{1}</a>' -f [System.Net.WebUtility]::HtmlEncode($full), [System.Net.WebUtility]::HtmlEncode($disp))
}
'@
#endregion

#region ---- Task catalogue ------------------------------------------------------------------
# Tasks are listed in the order they run when several are selected together.
$Actions     = @{}
$ActionOrder = New-Object System.Collections.Generic.List[string]

function Add-Action {
    param(
        [string]$Id, [string]$Category, [string]$Name, [string]$Desc,
        [string]$Preview, [string]$Script, [switch]$Reboot, [string]$Warning = ''
    )
    $script:Actions[$Id] = [pscustomobject]@{
        Id = $Id; Category = $Category; Name = $Name; Desc = $Desc; Preview = $Preview
        Script = $Script; Reboot = [bool]$Reboot; Warning = $Warning
    }
    $script:ActionOrder.Add($Id)
}

Add-Action -Id 'restorepoint' -Category 'Repair' -Name 'Create restore point' `
    -Desc 'Safety net: lets you roll Windows back if anything goes wrong. Run this first.' `
    -Preview 'Enable-ComputerRestore; Checkpoint-Computer -RestorePointType MODIFY_SETTINGS' -Script @'
Write-Log 'Making sure System Restore is on for the system drive...'
try { Enable-ComputerRestore -Drive ("{0}\" -f $env:SystemDrive) -ErrorAction Stop }
catch { Write-Log ('Could not enable System Restore: {0}' -f $_.Exception.Message) 'WARN' }
$w = $null
try {
    $rpLabel = [string]$Sync.RestoreLabel
    $rpDesc = if ($rpLabel) { 'BenchKit: {0} ({1:yyyy-MM-dd HH:mm})' -f $rpLabel, (Get-Date) } else { 'BenchKit {0:yyyy-MM-dd HH:mm}' -f (Get-Date) }
    Checkpoint-Computer -Description $rpDesc -RestorePointType 'MODIFY_SETTINGS' `
        -ErrorAction Stop -WarningVariable w -WarningAction SilentlyContinue
    if ($w) { Write-Log ('Windows skipped it: {0}' -f ($w -join ' ')) 'WARN' }
    else    { Write-Log ('Restore point created: {0}' -f $rpDesc) 'OK' }
} catch { Write-Log ('Restore point failed: {0}' -f $_.Exception.Message) 'WARN' }
'@

Add-Action -Id 'defender_update' -Category 'Security' -Name 'Update Defender definitions' `
    -Desc 'Downloads the latest Microsoft Defender virus definitions.' `
    -Preview 'Update-MpSignature' -Script @'
try { Update-MpSignature -ErrorAction Stop; Write-Log 'Defender definitions updated.' 'OK' }
catch { Write-Log ('Update failed (another antivirus may be in charge): {0}' -f $_.Exception.Message) 'WARN' }
'@

Add-Action -Id 'temp_user' -Category 'Cleanup' -Name 'Clear user temp files' `
    -Desc 'Deletes leftover temporary files in your profile. Files in use are skipped.' `
    -Preview 'Remove contents of %TEMP%' -Script @'
Clear-Folder $env:TEMP 'User temp'
'@

Add-Action -Id 'temp_win' -Category 'Cleanup' -Name 'Clear Windows temp files' `
    -Desc 'Deletes leftover temporary files used by Windows and installers.' `
    -Preview 'Remove contents of C:\Windows\Temp' -Script @'
Clear-Folder "$env:SystemRoot\Temp" 'Windows temp'
'@

Add-Action -Id 'browser_cache' -Category 'Cleanup' -Name 'Clear browser caches' `
    -Desc 'Empties the cache of Chrome, Edge, Brave and Firefox. Logins and bookmarks are NOT touched.' `
    -Preview 'Remove ...\User Data\*\Cache\Cache_Data and Firefox ...\Profiles\*\cache2' -Script @'
if (Get-Process chrome, msedge, firefox, brave -ErrorAction SilentlyContinue) {
    Write-Log 'Some browsers are open - their in-use cache files will be skipped. Close them for a full clean.' 'WARN'
}
Clear-Folder "$env:LOCALAPPDATA\Google\Chrome\User Data\*\Cache\Cache_Data" 'Chrome cache'
Clear-Folder "$env:LOCALAPPDATA\Microsoft\Edge\User Data\*\Cache\Cache_Data" 'Edge cache'
Clear-Folder "$env:LOCALAPPDATA\BraveSoftware\Brave-Browser\User Data\*\Cache\Cache_Data" 'Brave cache'
Clear-Folder "$env:LOCALAPPDATA\Mozilla\Firefox\Profiles\*\cache2" 'Firefox cache'
'@

Add-Action -Id 'wu_cache' -Category 'Cleanup' -Name 'Clear Windows Update download cache' `
    -Desc 'Removes already-downloaded update files. Windows re-downloads what it still needs.' `
    -Preview 'Stop wuauserv, bits; remove C:\Windows\SoftwareDistribution\Download\*; start services' -Script @'
Stop-Svc 'wuauserv', 'bits'
Clear-Folder "$env:SystemRoot\SoftwareDistribution\Download" 'Update download cache'
Start-Svc 'bits', 'wuauserv'
'@

Add-Action -Id 'do_cache' -Category 'Cleanup' -Name 'Clear Delivery Optimization cache' `
    -Desc 'Removes update files Windows keeps to share with other PCs.' `
    -Preview 'Delete-DeliveryOptimizationCache -Force' -Script @'
try { Delete-DeliveryOptimizationCache -Force -ErrorAction Stop; Write-Log 'Delivery Optimization cache cleared.' 'OK' }
catch { Write-Log ('Could not clear it: {0}' -f $_.Exception.Message) 'WARN' }
'@

Add-Action -Id 'dumps' -Category 'Cleanup' -Name 'Delete crash dumps and error reports' `
    -Desc 'Removes memory dumps and Windows Error Reporting files.' `
    -Warning 'Dumps are useful for diagnosing blue screens - analyse them first if the PC is crashing.' `
    -Preview 'Remove C:\Windows\Minidump\*, C:\Windows\MEMORY.DMP, %LOCALAPPDATA%\CrashDumps\*, WER queues' -Script @'
Clear-Folder "$env:SystemRoot\Minidump" 'Minidumps'
$big = "$env:SystemRoot\MEMORY.DMP"
if (Test-Path -LiteralPath $big) {
    $mb = [math]::Round((Get-Item -LiteralPath $big).Length / 1MB)
    Remove-Item -LiteralPath $big -Force -ErrorAction SilentlyContinue
    Write-Log ('MEMORY.DMP: freed {0} MB' -f $mb) 'OK'
}
Clear-Folder "$env:LOCALAPPDATA\CrashDumps" 'App crash dumps'
Clear-Folder "$env:ProgramData\Microsoft\Windows\WER\ReportArchive" 'Error report archive'
Clear-Folder "$env:ProgramData\Microsoft\Windows\WER\ReportQueue" 'Error report queue'
'@

Add-Action -Id 'recycle' -Category 'Cleanup' -Name 'Empty Recycle Bin' `
    -Desc 'Permanently deletes everything in the Recycle Bin on all drives.' `
    -Warning 'Files in the Recycle Bin cannot be recovered after this.' `
    -Preview 'Clear-RecycleBin -Force' -Script @'
Clear-RecycleBin -Force -ErrorAction SilentlyContinue
Write-Log 'Recycle Bin emptied.' 'OK'
'@

Add-Action -Id 'dism_check' -Category 'Repair' -Name 'DISM quick health check' `
    -Desc 'Fast check (seconds) for known corruption in the Windows image.' `
    -Preview 'dism.exe /Online /Cleanup-Image /CheckHealth' -Script @'
Invoke-Exe 'dism.exe' @('/Online', '/Cleanup-Image', '/CheckHealth') | Out-Null
'@

Add-Action -Id 'dism_scan' -Category 'Repair' -Name 'DISM full scan' `
    -Desc 'Thorough scan of the Windows image for corruption (5-15 min). Does not repair.' `
    -Preview 'dism.exe /Online /Cleanup-Image /ScanHealth' -Script @'
Invoke-Exe 'dism.exe' @('/Online', '/Cleanup-Image', '/ScanHealth') | Out-Null
'@

Add-Action -Id 'dism_restore' -Category 'Repair' -Name 'DISM repair Windows image' `
    -Desc 'Repairs the Windows image using Windows Update (10-30 min). Run before SFC.' `
    -Preview 'dism.exe /Online /Cleanup-Image /RestoreHealth' -Script @'
Invoke-Exe 'dism.exe' @('/Online', '/Cleanup-Image', '/RestoreHealth') | Out-Null
'@

Add-Action -Id 'sfc' -Category 'Repair' -Name 'System File Checker (SFC)' `
    -Desc 'Checks and repairs damaged Windows system files (10-20 min).' `
    -Preview 'sfc.exe /scannow' -Script @'
Invoke-Exe 'sfc.exe' @('/scannow') | Out-Null
Write-Log 'Full details: C:\Windows\Logs\CBS\CBS.log'
'@

Add-Action -Id 'dism_cleanup' -Category 'Cleanup' -Name 'Clean up old Windows components' `
    -Desc 'Removes superseded update files from WinSxS. Can free several GB.' `
    -Preview 'dism.exe /Online /Cleanup-Image /StartComponentCleanup' -Script @'
Invoke-Exe 'dism.exe' @('/Online', '/Cleanup-Image', '/StartComponentCleanup') | Out-Null
'@

Add-Action -Id 'chkdsk_scan' -Category 'Repair' -Name 'Check system drive for errors' `
    -Desc 'Online file-system scan of the system drive (no restart needed for the scan).' `
    -Preview 'chkdsk.exe C: /scan' -Script @'
Invoke-Exe 'chkdsk.exe' @($env:SystemDrive, '/scan') | Out-Null
'@

Add-Action -Id 'wmi_repair' -Category 'Repair' -Name 'Verify / repair WMI' `
    -Desc 'Checks the WMI repository many tools depend on and salvages it if inconsistent.' `
    -Preview 'winmgmt /verifyrepository  (then /salvagerepository if needed)' -Script @'
$c = Invoke-Exe 'winmgmt.exe' @('/verifyrepository')
if ($c -ne 0 -or (($global:LastExeOutput -join ' ') -match 'inconsistent|not consistent')) {
    Write-Log 'Repository is inconsistent - salvaging...' 'WARN'
    Invoke-Exe 'winmgmt.exe' @('/salvagerepository') | Out-Null
} else { Write-Log 'WMI repository is consistent.' 'OK' }
'@

Add-Action -Id 'wu_reset' -Category 'Repair' -Name 'Reset Windows Update components' `
    -Desc 'Fixes stuck or failing updates by resetting the update cache folders (old ones kept as backups).' `
    -Reboot -Preview 'Stop wuauserv, cryptSvc, bits, msiserver, usosvc; rename SoftwareDistribution and catroot2; start services' -Script @'
$svcs = 'wuauserv', 'usosvc', 'bits', 'cryptSvc', 'msiserver'
Stop-Svc $svcs
$stamp = Get-Date -Format 'yyyyMMddHHmmss'
foreach ($p in "$env:SystemRoot\SoftwareDistribution", "$env:SystemRoot\System32\catroot2") {
    if (Test-Path -LiteralPath $p) {
        try {
            Rename-Item -LiteralPath $p -NewName ('{0}.bak{1}' -f (Split-Path $p -Leaf), $stamp) -ErrorAction Stop
            Write-Log ('Renamed {0} (backup kept).' -f $p) 'OK'
        } catch { Write-Log ('Could not rename {0}: {1}' -f $p, $_.Exception.Message) 'WARN' }
    }
}
Start-Svc 'cryptSvc', 'bits', 'wuauserv', 'usosvc'
Write-Log 'Windows Update components reset. Restart, then check for updates.' 'OK'
'@

Add-Action -Id 'bits_fix' -Category 'Repair' -Name 'Fix Background Transfer (BITS)' `
    -Desc 'Clears stuck background-download jobs and restarts the BITS service - the equivalent of the old Windows BITS troubleshooter. Use when Windows Update, the Store or app downloads stall at 0%.' `
    -Preview 'Set BITS start=Manual; start BITS; remove all BITS transfer jobs (Remove-BitsTransfer / bitsadmin /reset); restart BITS' -Script @'
$svc = Get-Service BITS -ErrorAction SilentlyContinue
if (-not $svc) { Write-Log 'The BITS service was not found on this PC.' 'ERROR'; return }
# BITS is disabled on some broken PCs - restore its normal (Manual / trigger-start) startup.
try { Set-Service -Name BITS -StartupType Manual -ErrorAction Stop; Write-Log 'BITS startup set to Manual (Windows default).' 'OK' }
catch { Write-Log ('Could not set BITS startup: {0}' -f $_.Exception.Message) 'WARN' }
Start-Svc 'BITS'
$cleared = $false
if (Get-Command Get-BitsTransfer -ErrorAction SilentlyContinue) {
    try {
        $jobs = @(Get-BitsTransfer -AllUsers -ErrorAction Stop)
        Write-Log ('BITS has {0} transfer job(s) queued.' -f $jobs.Count)
        if ($jobs.Count) { $jobs | Remove-BitsTransfer -ErrorAction SilentlyContinue; Write-Log ('Cleared {0} stuck BITS job(s).' -f $jobs.Count) 'OK' }
        $cleared = $true
    } catch { Write-Log ('Get/Remove-BitsTransfer failed, trying bitsadmin: {0}' -f $_.Exception.Message) 'WARN' }
}
if (-not $cleared) {
    $ba = Join-Path $env:SystemRoot 'System32\bitsadmin.exe'
    if (Test-Path -LiteralPath $ba) {
        Write-Log 'Clearing BITS jobs via bitsadmin...'
        $r = (& $ba /reset /allusers 2>&1 | Out-String)
        foreach ($ln in ($r -split "`r?`n")) { if ($ln.Trim()) { Write-Log $ln 'OUT' } }
    }
}
# Restart to settle the service.
Stop-Svc 'BITS'
Start-Svc 'BITS'
$svc2 = Get-Service BITS -ErrorAction SilentlyContinue
if ($svc2 -and $svc2.Status -eq 'Running') { Write-Log 'BITS is running and stuck transfers are cleared.' 'DONE' }
else { Write-Log 'BITS did not start - check its dependencies (RpcSs, EventSystem).' 'WARN' }
'@

Add-Action -Id 'time_sync' -Category 'Repair' -Name 'Sync the clock' `
    -Desc 'Resyncs Windows time. A wrong clock breaks updates, HTTPS sites and activation.' `
    -Preview 'Start w32time; w32tm /resync /force' -Script @'
Start-Svc 'w32time'
Invoke-Exe 'w32tm.exe' @('/resync', '/force') | Out-Null
'@

Add-Action -Id 'spooler_fix' -Category 'Repair' -Name 'Fix stuck print queue' `
    -Desc 'Clears stuck print jobs and restarts the Print Spooler.' `
    -Preview 'Stop Spooler; remove C:\Windows\System32\spool\PRINTERS\*; start Spooler' -Script @'
Stop-Svc 'Spooler'
Clear-Folder "$env:SystemRoot\System32\spool\PRINTERS" 'Print queue'
Start-Svc 'Spooler'
'@

Add-Action -Id 'icon_cache' -Category 'Repair' -Name 'Rebuild icon and thumbnail cache' `
    -Desc 'Fixes blank, wrong or missing icons and thumbnails. Explorer restarts briefly.' `
    -Preview 'Stop explorer; delete IconCache.db, iconcache_*.db, thumbcache_*.db; start explorer' -Script @'
Get-Process explorer -ErrorAction SilentlyContinue | Stop-Process -Force
Start-Sleep -Seconds 2
Remove-Item "$env:LOCALAPPDATA\IconCache.db" -Force -ErrorAction SilentlyContinue
Get-ChildItem "$env:LOCALAPPDATA\Microsoft\Windows\Explorer" -Filter '*cache_*.db' -Force -ErrorAction SilentlyContinue |
    Remove-Item -Force -ErrorAction SilentlyContinue
Start-Sleep -Seconds 3
if (-not (Get-Process explorer -ErrorAction SilentlyContinue)) { Start-Process explorer.exe }
Write-Log 'Icon and thumbnail caches rebuilt.' 'OK'
'@

Add-Action -Id 'explorer_restart' -Category 'Repair' -Name 'Restart Windows Explorer' `
    -Desc 'Fixes a frozen taskbar, Start menu or desktop.' `
    -Preview 'Stop-Process explorer; start explorer' -Script @'
Get-Process explorer -ErrorAction SilentlyContinue | Stop-Process -Force
Start-Sleep -Seconds 4
if (-not (Get-Process explorer -ErrorAction SilentlyContinue)) { Start-Process explorer.exe }
Write-Log 'Explorer restarted.' 'OK'
'@

Add-Action -Id 'net_test' -Category 'Network' -Name 'Test connection' `
    -Desc 'Checks gateway, internet, DNS and web access, and lists DNS servers in use.' `
    -Preview 'Test-Connection gateway / 1.1.1.1; Resolve-DnsName; HTTP test to msftconnecttest.com' -Script @'
$gw = (Get-NetRoute -DestinationPrefix '0.0.0.0/0' -ErrorAction SilentlyContinue | Sort-Object RouteMetric | Select-Object -First 1).NextHop
if ($gw) {
    if (Test-Connection $gw -Count 2 -Quiet) { Write-Log ('Router/gateway {0} reachable.' -f $gw) 'OK' }
    else { Write-Log ('Router/gateway {0} NOT reachable.' -f $gw) 'WARN' }
} else { Write-Log 'No default gateway - the PC is not connected to a network.' 'WARN' }
if (Test-Connection 1.1.1.1 -Count 2 -Quiet) { Write-Log 'Internet reachable by IP address.' 'OK' }
else { Write-Log 'Internet NOT reachable by IP address.' 'WARN' }
try {
    $r = Resolve-DnsName www.microsoft.com -Type A -DnsOnly -ErrorAction Stop | Where-Object { $_.IPAddress } | Select-Object -First 1
    Write-Log ('DNS works (www.microsoft.com -> {0}).' -f $r.IPAddress) 'OK'
} catch { Write-Log 'DNS lookups are failing.' 'WARN' }
try {
    $w = Invoke-WebRequest 'http://www.msftconnecttest.com/connecttest.txt' -UseBasicParsing -TimeoutSec 8 -ErrorAction Stop
    if ($w.Content -match 'Microsoft Connect Test') { Write-Log 'Web access works.' 'OK' }
    else { Write-Log 'Web access is being redirected (hotel/guest Wi-Fi login page or proxy?).' 'WARN' }
} catch { Write-Log ('Web test failed: {0}' -f $_.Exception.Message) 'WARN' }
Get-DnsClientServerAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object { $_.ServerAddresses } | ForEach-Object {
    Write-Log ('DNS servers on {0}: {1}' -f $_.InterfaceAlias, ($_.ServerAddresses -join ', '))
}
'@

Add-Action -Id 'speedtest' -Category 'Network' -Name 'Internet speed test' `
    -Desc 'Measures download/upload speed and latency. Run one labelled "Before" and another "After" your fixes - both land on the report so you can show the improvement.' `
    -Preview 'Timed download/upload against speed.cloudflare.com; ping to 1.1.1.1' -Script @'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$label = [string]$Sync.SpeedLabel
Write-Log ('Running internet speed test{0}...' -f $(if ($label) { " ($label)" } else { '' })) 'STEP'
$ping = $null
try { $pr = Test-Connection 1.1.1.1 -Count 4 -ErrorAction Stop; $ping = [math]::Round(($pr | Measure-Object -Property ResponseTime -Average).Average) } catch { }
if ($null -ne $ping) { Write-Log ('Latency (ping 1.1.1.1): {0} ms' -f $ping) 'OK' } else { Write-Log 'Latency: could not ping 1.1.1.1.' 'WARN' }
$down = $null
try {
    $bytes = 25000000
    $Sync.Status = 'Testing download speed...'
    $sw = [System.Diagnostics.Stopwatch]::StartNew()
    $r = Invoke-WebRequest ('https://speed.cloudflare.com/__down?bytes={0}' -f $bytes) -UseBasicParsing -TimeoutSec 60 -ErrorAction Stop
    $sw.Stop()
    $got = [double]$r.RawContentLength; if ($got -le 0) { $got = $bytes }
    if ($sw.Elapsed.TotalSeconds -gt 0) { $down = [math]::Round((($got * 8) / 1000000) / $sw.Elapsed.TotalSeconds, 1) }
    Write-Log ('Download: {0} Mbps' -f $down) 'OK'
} catch { Write-Log ('Download test failed: {0}' -f $_.Exception.Message) 'WARN' }
$up = $null
try {
    $Sync.Status = 'Testing upload speed...'
    $payload = New-Object byte[] (10000000)
    $sw2 = [System.Diagnostics.Stopwatch]::StartNew()
    Invoke-WebRequest 'https://speed.cloudflare.com/__up' -Method Post -Body $payload -UseBasicParsing -TimeoutSec 60 -ErrorAction Stop | Out-Null
    $sw2.Stop()
    if ($sw2.Elapsed.TotalSeconds -gt 0) { $up = [math]::Round((($payload.Length * 8) / 1000000) / $sw2.Elapsed.TotalSeconds, 1) }
    Write-Log ('Upload: {0} Mbps' -f $up) 'OK'
} catch { Write-Log ('Upload test failed: {0}' -f $_.Exception.Message) 'WARN' }
$rec = [pscustomobject]@{
    Time = (Get-Date).ToString('yyyy-MM-dd HH:mm'); Label = $(if ($label) { $label } else { '-' })
    Download = $(if ($null -ne $down) { '{0} Mbps' -f $down } else { 'n/a' })
    Upload = $(if ($null -ne $up) { '{0} Mbps' -f $up } else { 'n/a' })
    Ping = $(if ($null -ne $ping) { '{0} ms' -f $ping } else { 'n/a' })
}
[void]$Sync.SpeedTests.Add($rec)
Write-Log ('Speed test complete - down {0} / up {1} / ping {2}. Added to the report.' -f $rec.Download, $rec.Upload, $rec.Ping) 'DONE'
'@

Add-Action -Id 'dns_flush' -Category 'Network' -Name 'Flush DNS cache' `
    -Desc 'Clears cached website addresses. Fixes sites that will not load after changes.' `
    -Preview 'ipconfig /flushdns' -Script @'
Invoke-Exe 'ipconfig.exe' @('/flushdns') | Out-Null
'@

Add-Action -Id 'arp_flush' -Category 'Network' -Name 'Clear ARP cache' `
    -Desc 'Clears cached local network addresses.' `
    -Preview 'netsh interface ip delete arpcache' -Script @'
Invoke-Exe 'netsh.exe' @('interface', 'ip', 'delete', 'arpcache') | Out-Null
'@

Add-Action -Id 'proxy_reset' -Category 'Network' -Name 'Reset proxy settings' `
    -Desc 'Removes proxy settings (often left behind by adware) that can block the internet.' `
    -Preview 'netsh winhttp reset proxy; set HKCU Internet Settings ProxyEnable=0, remove ProxyServer/AutoConfigURL' -Script @'
Invoke-Exe 'netsh.exe' @('winhttp', 'reset', 'proxy') | Out-Null
$k = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'
Set-ItemProperty -Path $k -Name ProxyEnable -Value 0 -ErrorAction SilentlyContinue
Remove-ItemProperty -Path $k -Name ProxyServer, AutoConfigURL -ErrorAction SilentlyContinue
Write-Log 'Proxy settings cleared.' 'OK'
'@

Add-Action -Id 'hosts_reset' -Category 'Network' -Name 'Reset hosts file' `
    -Desc 'Restores the default hosts file (malware often uses it to redirect sites). A backup is kept.' `
    -Warning 'Any intentional custom entries (e.g. for development or blocking) will be removed - a backup is saved next to it.' `
    -Preview 'Back up C:\Windows\System32\drivers\etc\hosts; write default; ipconfig /flushdns' -Script @'
$h = "$env:SystemRoot\System32\drivers\etc\hosts"
$bak = '{0}.bak{1:yyyyMMddHHmmss}' -f $h, (Get-Date)
Copy-Item -LiteralPath $h -Destination $bak -Force -ErrorAction SilentlyContinue
$default = @(
    '# Hosts file - reset to a clean state by BenchKit.'
    '# The previous version was saved alongside this file (hosts.bak<date>).'
    '# Add entries as: <IP address> <host name>   e.g.  10.0.0.5  nas.local'
    '# Windows resolves localhost by itself, so no entries are needed by default.'
)
Set-Content -LiteralPath $h -Value $default -Encoding ASCII
Write-Log ('Hosts file reset. Backup: {0}' -f $bak) 'OK'
Invoke-Exe 'ipconfig.exe' @('/flushdns') | Out-Null
'@

Add-Action -Id 'firewall_on' -Category 'Security' -Name 'Turn Windows Firewall on' `
    -Desc 'Enables the firewall for Domain, Private and Public networks.' `
    -Preview 'Set-NetFirewallProfile -Profile Domain,Private,Public -Enabled True' -Script @'
Set-NetFirewallProfile -Profile Domain, Private, Public -Enabled True -ErrorAction Stop
Write-Log 'Firewall enabled on all profiles.' 'OK'
'@

Add-Action -Id 'adapter_restart' -Category 'Network' -Name 'Restart network adapters' `
    -Desc 'Disables and re-enables active network adapters.' `
    -Warning 'Drops the connection for a few seconds - remote support sessions will disconnect.' `
    -Preview 'Get-NetAdapter | Where Status -eq Up | Restart-NetAdapter' -Script @'
$up = @(Get-NetAdapter -ErrorAction SilentlyContinue | Where-Object Status -eq 'Up')
foreach ($a in $up) {
    Write-Log ('Restarting {0}...' -f $a.Name)
    Restart-NetAdapter -Name $a.Name -Confirm:$false -ErrorAction SilentlyContinue
}
Start-Sleep -Seconds 5
Write-Log ('Restarted {0} adapter(s).' -f $up.Count) 'OK'
'@

Add-Action -Id 'ip_renew' -Category 'Network' -Name 'Release and renew IP address' `
    -Desc 'Gets a fresh IP address from the router.' `
    -Warning 'Drops the connection briefly - remote support sessions will disconnect.' `
    -Preview 'ipconfig /release; ipconfig /renew' -Script @'
Invoke-Exe 'ipconfig.exe' @('/release') | Out-Null
Invoke-Exe 'ipconfig.exe' @('/renew') | Out-Null
'@

Add-Action -Id 'winsock' -Category 'Network' -Name 'Reset Winsock' `
    -Desc 'Repairs the Windows network socket catalog (fixes many "connected, no internet" cases).' `
    -Reboot -Preview 'netsh winsock reset' -Script @'
Invoke-Exe 'netsh.exe' @('winsock', 'reset') | Out-Null
'@

Add-Action -Id 'tcpip' -Category 'Network' -Name 'Reset TCP/IP stack' `
    -Desc 'Resets TCP/IP settings to defaults.' `
    -Warning 'Static IP addresses are cleared - note them down first if this PC uses one.' `
    -Reboot -Preview 'netsh int ip reset' -Script @'
Invoke-Exe 'netsh.exe' @('int', 'ip', 'reset') | Out-Null
'@

Add-Action -Id 'defender_quick' -Category 'Security' -Name 'Defender quick scan' `
    -Desc 'Scans the places malware usually hides (5-15 min).' `
    -Preview 'Start-MpScan -ScanType QuickScan' -Script @'
try {
    Start-MpScan -ScanType QuickScan -ErrorAction Stop
    $t = @(Get-MpThreatDetection -ErrorAction SilentlyContinue | Where-Object { $_.InitialDetectionTime -gt (Get-Date).AddHours(-2) })
    if ($t.Count) { Write-Log ('{0} threat(s) detected - see Windows Security > Protection history.' -f $t.Count) 'WARN' }
    else { Write-Log 'Quick scan finished: no threats found.' 'OK' }
} catch { Write-Log ('Scan could not run: {0}' -f $_.Exception.Message) 'WARN' }
'@

Add-Action -Id 'defender_full' -Category 'Security' -Name 'Defender full scan' `
    -Desc 'Scans every file on the PC.' `
    -Warning 'Takes a long time (often 1-3 hours).' `
    -Preview 'Start-MpScan -ScanType FullScan' -Script @'
try {
    Start-MpScan -ScanType FullScan -ErrorAction Stop
    $t = @(Get-MpThreatDetection -ErrorAction SilentlyContinue | Where-Object { $_.InitialDetectionTime -gt (Get-Date).AddHours(-6) })
    if ($t.Count) { Write-Log ('{0} threat(s) detected - see Windows Security > Protection history.' -f $t.Count) 'WARN' }
    else { Write-Log 'Full scan finished: no threats found.' 'OK' }
} catch { Write-Log ('Scan could not run: {0}' -f $_.Exception.Message) 'WARN' }
'@

Add-Action -Id 'defender_threats' -Category 'Security' -Name 'Show recent threat detections' `
    -Desc 'Lists what Defender has detected recently.' `
    -Preview 'Get-MpThreatDetection | Get-MpThreat' -Script @'
$d = @(Get-MpThreatDetection -ErrorAction SilentlyContinue | Sort-Object InitialDetectionTime -Descending | Select-Object -First 25)
if (-not $d.Count) { Write-Log 'No threat detections recorded.' 'OK'; return }
$names = @{}
Get-MpThreat -ErrorAction SilentlyContinue | ForEach-Object { $names[[string]$_.ThreatID] = $_.ThreatName }
foreach ($x in $d) {
    Write-Log ('{0:yyyy-MM-dd HH:mm}  {1}  {2}' -f $x.InitialDetectionTime, $names[[string]$x.ThreatID], ($x.Resources -join '; ')) 'WARN'
}
'@

# One-click installs of popular tech tools through winget (shown on the Tools tab).
# Each entry: display name = @(winget id, what the tool is - shown in the review box).
$WingetApps = [ordered]@{
    'Autoruns'          = @('Microsoft.Sysinternals.Autoruns', 'Sysinternals tool that shows EVERYTHING set to auto-start (programs, services, drivers, scheduled tasks, shell add-ons) so you can disable malware/bloat that Task Manager misses.')
    'Process Explorer'  = @('Microsoft.Sysinternals.ProcessExplorer', 'A supercharged Task Manager from Sysinternals - shows what each process really is, its parent, open files/handles, and can check files against VirusTotal.')
    'Malwarebytes'      = @('Malwarebytes.Malwarebytes', 'Popular anti-malware scanner/remover, good at adware and PUPs the built-in antivirus leaves behind.')
    'HWiNFO'            = @('REALiX.HWiNFO', 'Deep hardware info and live sensors - temperatures, fan speeds, voltages, drive health. Good for diagnosing overheating or failing parts.')
    'CrystalDiskInfo'   = @('CrystalDewWorld.CrystalDiskInfo', 'Reads a drive''s SMART health data and shows a clear Good/Caution/Bad verdict plus temperature and power-on hours.')
    'WizTree'           = @('AntibodySoftware.WizTree', 'Scans a drive in seconds and shows what is using the space, biggest files/folders first - for freeing up a full disk.')
    'Revo Uninstaller'  = @('RevoUninstaller.RevoUninstaller', 'Removes stubborn programs and then cleans up the leftover files and registry entries a normal uninstall leaves behind.')
    '7-Zip'             = @('7zip.7zip', 'Free file archiver - opens and creates .zip, .7z, .rar and most other archive formats.')
}
foreach ($appName in $WingetApps.Keys) {
    $wid = $WingetApps[$appName][0]
    $wdesc = $WingetApps[$appName][1]
    $body = @'
$wg = Get-WingetPath
if (-not $wg) { Write-Log 'winget is not available. Install "App Installer" from the Microsoft Store.' 'ERROR'; return }
Invoke-Exe $wg @('install', '--id', '__ID__', '-e', '--silent', '--accept-package-agreements', '--accept-source-agreements') | Out-Null
'@
    Add-Action -Id ('inst_' + $wid) -Category 'Install' -Name ('Install ' + $appName) `
        -Desc ('{0}  (installed with winget)' -f $wdesc) `
        -Preview ('winget install --id {0} -e --silent' -f $wid) -Script ($body -replace '__ID__', $wid)
}

$Presets = [ordered]@{
    'Quick Tune-up'         = @('restorepoint', 'temp_user', 'temp_win', 'browser_cache', 'do_cache', 'dns_flush', 'dism_check')
    'Deep System Repair'    = @('restorepoint', 'dism_restore', 'sfc', 'dism_cleanup', 'chkdsk_scan', 'wmi_repair')
    'Windows Update Fix'    = @('restorepoint', 'time_sync', 'wu_reset', 'dism_restore', 'sfc')
    'Network Fix'           = @('net_test', 'dns_flush', 'arp_flush', 'proxy_reset', 'winsock', 'tcpip')
    'Malware Clean-up Prep' = @('restorepoint', 'defender_update', 'temp_user', 'temp_win', 'browser_cache', 'proxy_reset', 'defender_quick')
    'Free Up Space'         = @('temp_user', 'temp_win', 'browser_cache', 'wu_cache', 'do_cache', 'dumps', 'recycle', 'dism_cleanup')
}
#endregion

#region ---- Background scripts -------------------------------------------------------------
$RunnerScript = @'
$total = @($Items).Count
$n = 0
foreach ($item in $Items) {
    if ($Sync.Cancel) { Write-Log 'Stopped by user - remaining tasks skipped.' 'WARN'; break }
    $n++
    $Sync.Progress = $n - 1
    $Sync.Status   = ('[{0}/{1}] {2}' -f $n, $total, $item.Name)
    Write-Log ('=== {0} ===' -f $item.Name) 'STEP'
    $global:StepWarn = $false
    $start  = Get-Date
    $result = 'Completed'
    try {
        $sb = [scriptblock]::Create($item.Script)
        & $sb | Out-Null
        if ($global:StepWarn) { $result = 'Completed with warnings' }
    } catch {
        $result = 'Failed'
        Write-Log $_.Exception.Message 'ERROR'
    }
    $secs = [int]((Get-Date) - $start).TotalSeconds
    Write-Log ('{0}: {1} ({2}s)' -f $item.Name, $result, $secs) 'DONE'
    [void]$Sync.WorkDone.Add([pscustomobject]@{ Time = $start.ToString('yyyy-MM-dd HH:mm'); Task = $item.Name; Result = $result; Seconds = $secs })
    if ($item.Reboot -and $result -ne 'Failed') { $Sync.RebootNeeded = $true }
}
$Sync.Progress = $total
'@

$DiagScript = @'
$f = New-Object System.Collections.ArrayList
function Add-Finding([string]$Severity, [string]$Area, [string]$Finding, [string[]]$Fix = @()) {
    [void]$f.Add([pscustomobject]@{ Severity = $Severity; Area = $Area; Finding = $Finding; Fix = $Fix })
}
function Get-EventCount([hashtable]$Filter) {
    try { return @(Get-WinEvent -FilterHashtable $Filter -ErrorAction Stop).Count } catch { return 0 }
}
Write-Log 'Smart Diagnostics started.' 'STEP'
$since30 = (Get-Date).AddDays(-30)
$since7  = (Get-Date).AddDays(-7)

# ---- Storage
$Sync.Status = 'Checking storage...'
try {
    $d    = New-Object System.IO.DriveInfo($env:SystemDrive)
    $free = [math]::Round($d.AvailableFreeSpace / 1GB, 1)
    $pct  = [math]::Round($d.AvailableFreeSpace / $d.TotalSize * 100, 1)
    $msg  = 'System drive: {0} GB free ({1}%).' -f $free, $pct
    if ($pct -lt 10)     { Add-Finding 'Critical' 'Storage' ($msg + ' Windows needs room to update and run well.') @('temp_user', 'temp_win', 'wu_cache', 'do_cache', 'dism_cleanup') }
    elseif ($pct -lt 20) { Add-Finding 'Warning' 'Storage' $msg @('temp_user', 'temp_win', 'wu_cache', 'do_cache') }
    else                 { Add-Finding 'OK' 'Storage' $msg }
} catch { }
$tmp = (Get-SizeMB $env:TEMP) + (Get-SizeMB "$env:SystemRoot\Temp")
if ($tmp -gt 1024)   { Add-Finding 'Warning' 'Storage' ('Temporary files are using {0:N0} MB.' -f $tmp) @('temp_user', 'temp_win') }
elseif ($tmp -gt 200) { Add-Finding 'Info' 'Storage' ('Temporary files are using {0:N0} MB.' -f $tmp) @('temp_user', 'temp_win') }

# ---- Hardware
$Sync.Status = 'Checking hardware...'
try {
    foreach ($pd in @(Get-PhysicalDisk -ErrorAction Stop)) {
        if ($pd.HealthStatus -ne 'Healthy') { Add-Finding 'Critical' 'Hardware' ('Drive "{0}" reports health: {1}. Back up data now.' -f $pd.FriendlyName, $pd.HealthStatus) @('chkdsk_scan') }
        else { Add-Finding 'OK' 'Hardware' ('Drive "{0}" ({1}) is healthy.' -f $pd.FriendlyName, $pd.MediaType) }
    }
} catch { }
try {
    $pf = @(Get-CimInstance -Namespace root\wmi -ClassName MSStorageDriver_FailurePredictStatus -ErrorAction Stop | Where-Object PredictFailure)
    if ($pf.Count) { Add-Finding 'Critical' 'Hardware' 'SMART predicts a drive failure. Back up data immediately and replace the drive.' }
} catch { }
$diskErr = Get-EventCount @{ LogName = 'System'; ProviderName = 'disk', 'Ntfs'; Level = 1, 2, 3; StartTime = $since30 }
if ($diskErr -gt 0) { Add-Finding 'Warning' 'Hardware' ('{0} disk / file-system errors logged in the last 30 days.' -f $diskErr) @('chkdsk_scan') }
try {
    $bad = @(Get-PnpDevice -PresentOnly -Status ERROR, DEGRADED -ErrorAction Stop)
    if ($bad.Count) { Add-Finding 'Warning' 'Hardware' ('{0} device(s) with driver problems: {1}. Check Device Manager.' -f $bad.Count, ((@($bad | Select-Object -First 4 -ExpandProperty FriendlyName)) -join '; ')) }
    else { Add-Finding 'OK' 'Hardware' 'All devices have working drivers.' }
} catch { }
try {
    $bs = Get-CimInstance -Namespace root\wmi -ClassName BatteryStaticData -ErrorAction Stop | Select-Object -First 1
    $bf = Get-CimInstance -Namespace root\wmi -ClassName BatteryFullChargedCapacity -ErrorAction Stop | Select-Object -First 1
    if ($bs.DesignedCapacity -gt 0 -and $bf.FullChargedCapacity -gt 0) {
        $wear = [math]::Round(100 - ($bf.FullChargedCapacity / $bs.DesignedCapacity * 100))
        if ($wear -ge 40) { Add-Finding 'Warning' 'Hardware' ('Battery has lost about {0}% of its original capacity - consider replacing it.' -f $wear) }
        else { Add-Finding 'Info' 'Hardware' ('Battery wear: about {0}%.' -f [math]::Max(0, $wear)) }
    }
} catch { }

# ---- Stability
$Sync.Status = 'Reading event logs...'
$bsod = Get-EventCount @{ LogName = 'System'; ProviderName = 'Microsoft-Windows-WER-SystemErrorReporting'; Id = 1001; StartTime = $since30 }
if ($bsod) { Add-Finding 'Critical' 'Stability' ('{0} blue-screen crash(es) in the last 30 days.' -f $bsod) @('dism_restore', 'sfc', 'chkdsk_scan') }
$kp = Get-EventCount @{ LogName = 'System'; ProviderName = 'Microsoft-Windows-Kernel-Power'; Id = 41; StartTime = $since30 }
if ($kp) { Add-Finding 'Warning' 'Stability' ('{0} unexpected shutdown(s) or power loss in the last 30 days.' -f $kp) }
$appCrash = Get-EventCount @{ LogName = 'Application'; Id = 1000; StartTime = $since7 }
if ($appCrash -ge 10) { Add-Finding 'Warning' 'Stability' ('{0} application crashes in the last 7 days.' -f $appCrash) @('dism_restore', 'sfc') }
elseif ($appCrash)    { Add-Finding 'Info' 'Stability' ('{0} application crash(es) in the last 7 days.' -f $appCrash) }
if (-not $bsod -and $appCrash -lt 10) { Add-Finding 'OK' 'Stability' 'No significant crash activity.' }

# ---- System
$Sync.Status = 'Checking Windows...'
$os = Get-CimInstance Win32_OperatingSystem
$up = (Get-Date) - $os.LastBootUpTime
if ($up.TotalDays -gt 14) { Add-Finding 'Warning' 'System' ('Not restarted in {0:N0} days. A restart clears many problems.' -f $up.TotalDays) }
$pending = (Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending') -or
           (Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired')
if ($pending) { Add-Finding 'Warning' 'System' 'A restart is pending to finish installing updates.' }
try {
    $lic = Get-CimInstance SoftwareLicensingProduct -Filter "PartialProductKey IS NOT NULL AND ApplicationID='55c92734-d682-4d71-983e-d6ec3f16059f'" -ErrorAction Stop | Select-Object -First 1
    if ($lic -and $lic.LicenseStatus -ne 1) { Add-Finding 'Warning' 'System' 'Windows does not appear to be activated.' @('time_sync') }
    elseif ($lic) { Add-Finding 'OK' 'System' 'Windows is activated.' }
} catch { }
foreach ($svcName in 'Dhcp', 'Dnscache', 'EventLog', 'Winmgmt', 'Audiosrv', 'Spooler', 'BFE', 'mpssvc', 'Wcmsvc') {
    $s = Get-Service -Name $svcName -ErrorAction SilentlyContinue
    if ($s -and $s.StartType -eq 'Automatic' -and $s.Status -ne 'Running') {
        $fix = @(); if ($svcName -eq 'Spooler') { $fix = @('spooler_fix') }
        Add-Finding 'Warning' 'Services' ('"{0}" should be running but is {1}.' -f $s.DisplayName, $s.Status) $fix
    }
}

# ---- Performance
$memPct  = [math]::Round((1 - $os.FreePhysicalMemory / $os.TotalVisibleMemorySize) * 100)
$totalGB = [math]::Round($os.TotalVisibleMemorySize / 1MB, 1)
if ($memPct -gt 85) { Add-Finding 'Warning' 'Performance' ('Memory usage is high right now ({0}%).' -f $memPct) }
if ($totalGB -lt 7.5) { Add-Finding 'Info' 'Performance' ('Only {0} GB of RAM installed; 8 GB or more is recommended.' -f $totalGB) }
$su = @(Get-CimInstance Win32_StartupCommand -ErrorAction SilentlyContinue)
if ($su.Count -gt 15) { Add-Finding 'Warning' 'Performance' ('{0} programs start with Windows. Disable unneeded ones (Tools > Startup Apps).' -f $su.Count) }
else { Add-Finding 'OK' 'Performance' ('{0} startup programs.' -f $su.Count) }

# ---- Updates
$Sync.Status = 'Checking updates...'
$wu = Get-Service wuauserv -ErrorAction SilentlyContinue
if ($wu -and $wu.StartType -eq 'Disabled') { Add-Finding 'Critical' 'Updates' 'The Windows Update service is disabled.' @('wu_reset') }
$last = Get-HotFix -ErrorAction SilentlyContinue | Where-Object InstalledOn | Sort-Object InstalledOn -Descending | Select-Object -First 1
if ($last) {
    $age = ((Get-Date) - $last.InstalledOn).Days
    if ($age -gt 60) { Add-Finding 'Warning' 'Updates' ('The last update was installed {0} days ago ({1}).' -f $age, $last.HotFixID) @('time_sync', 'wu_reset') }
    else { Add-Finding 'OK' 'Updates' ('Latest update installed {0} days ago.' -f $age) }
}

# ---- Security
$Sync.Status = 'Checking security...'
try {
    $mp = Get-MpComputerStatus -ErrorAction Stop
    if ($mp.AMRunningMode -and $mp.AMRunningMode -ne 'Normal') {
        Add-Finding 'Info' 'Security' ('Microsoft Defender is in "{0}" mode (another antivirus is probably active).' -f $mp.AMRunningMode)
    } else {
        if (-not $mp.RealTimeProtectionEnabled) { Add-Finding 'Critical' 'Security' 'Defender real-time protection is OFF.' }
        if ($mp.AntivirusSignatureAge -gt 3) { Add-Finding 'Warning' 'Security' ('Defender definitions are {0} days old.' -f $mp.AntivirusSignatureAge) @('defender_update') }
        if ($mp.QuickScanAge -gt 14) {
            $txt = if ($mp.QuickScanAge -gt 3650) { 'Defender has never run a quick scan.' } else { 'No Defender scan in {0} days.' -f $mp.QuickScanAge }
            Add-Finding 'Info' 'Security' $txt @('defender_update', 'defender_quick')
        }
        if ($mp.RealTimeProtectionEnabled -and $mp.AntivirusSignatureAge -le 3) { Add-Finding 'OK' 'Security' 'Defender is on and up to date.' }
    }
} catch {
    $av = @(Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntiVirusProduct -ErrorAction SilentlyContinue)
    if ($av.Count) { Add-Finding 'Info' 'Security' ('Antivirus: {0}' -f (($av | Select-Object -ExpandProperty displayName) -join ', ')) }
    else { Add-Finding 'Warning' 'Security' 'Could not detect an active antivirus.' }
}
try {
    $off = @(Get-NetFirewallProfile -ErrorAction Stop | Where-Object { [string]$_.Enabled -eq 'False' })
    if ($off.Count) { Add-Finding 'Warning' 'Security' ('Firewall is off for: {0}' -f (($off | Select-Object -ExpandProperty Name) -join ', ')) @('firewall_on') }
    else { Add-Finding 'OK' 'Security' 'Firewall is on.' }
} catch { }

# ---- Network
$Sync.Status = 'Checking network...'
$ipOk  = Test-Connection 1.1.1.1 -Count 1 -Quiet -ErrorAction SilentlyContinue
$dnsOk = $false
try { Resolve-DnsName www.microsoft.com -DnsOnly -Type A -ErrorAction Stop | Out-Null; $dnsOk = $true } catch { }
if (-not $ipOk -and -not $dnsOk) { Add-Finding 'Critical' 'Network' 'No internet connection.' @('net_test', 'dns_flush', 'proxy_reset', 'winsock', 'tcpip') }
elseif ($ipOk -and -not $dnsOk)  { Add-Finding 'Warning' 'Network' 'Internet works by IP address but DNS lookups fail.' @('dns_flush', 'proxy_reset') }
else                             { Add-Finding 'OK' 'Network' 'Internet and DNS are working.' }
$ie = Get-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' -ErrorAction SilentlyContinue
if ($ie.ProxyEnable -eq 1) { Add-Finding 'Info' 'Network' ('A manual proxy is set ({0}). If unexpected, it may be adware.' -f $ie.ProxyServer) @('proxy_reset') }
$hostsEntries = @(Get-Content "$env:SystemRoot\System32\drivers\etc\hosts" -ErrorAction SilentlyContinue | Where-Object { $_ -match '^\s*[^#\s]' })
if ($hostsEntries.Count) { Add-Finding 'Info' 'Network' ('The hosts file has {0} custom entr(ies). Review them if sites redirect unexpectedly.' -f $hostsEntries.Count) @('hosts_reset') }

$Sync.Findings = $f.ToArray()
$crit = @($f | Where-Object Severity -eq 'Critical').Count
$warn = @($f | Where-Object Severity -eq 'Warning').Count
Write-Log ('Smart Diagnostics finished: {0} critical, {1} warning(s).' -f $crit, $warn) 'DONE'
'@

$ReportScript = @'
function HtmlEnc($v) { [System.Net.WebUtility]::HtmlEncode([string]$v) }
function Get-HtmlTable($Rows, [string[]]$Cols) {
    $Rows = @($Rows | Where-Object { $_ })
    if (-not $Rows.Count) { return '<p class="muted">None found.</p>' }
    $sb = New-Object System.Text.StringBuilder
    [void]$sb.Append('<table><tr>')
    foreach ($c in $Cols) { [void]$sb.Append('<th>' + (HtmlEnc $c) + '</th>') }
    [void]$sb.Append('</tr>')
    foreach ($r in $Rows) {
        $cls = ''
        if ($r.PSObject.Properties['Severity']) { $cls = ' class="sev-' + ([string]$r.Severity).ToLower() + '"' }
        [void]$sb.Append("<tr$cls>")
        foreach ($c in $Cols) { [void]$sb.Append('<td>' + (HtmlEnc $r.$c) + '</td>') }
        [void]$sb.Append('</tr>')
    }
    [void]$sb.Append('</table>')
    return $sb.ToString()
}
function Get-HtmlKV([System.Collections.IDictionary]$D) {
    $s = '<table class="kv">'
    foreach ($k in $D.Keys) { $s += '<tr><th>' + (HtmlEnc $k) + '</th><td>' + (HtmlEnc $D[$k]) + '</td></tr>' }
    return $s + '</table>'
}
function Section([string]$Title, [string]$Body) { return "<section><h2>$(HtmlEnc $Title)</h2>$Body</section>" }

Write-Log 'Building customer report...' 'STEP'
$Sync.Status = 'Collecting system details...'
$cs   = Get-CimInstance Win32_ComputerSystem
$bios = Get-CimInstance Win32_BIOS
$os   = Get-CimInstance Win32_OperatingSystem
$cpu  = Get-CimInstance Win32_Processor | Select-Object -First 1
$cv   = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -ErrorAction SilentlyContinue
$act  = 'Unknown'
try {
    $lic = Get-CimInstance SoftwareLicensingProduct -Filter "PartialProductKey IS NOT NULL AND ApplicationID='55c92734-d682-4d71-983e-d6ec3f16059f'" -ErrorAction Stop | Select-Object -First 1
    if ($lic) { $act = if ($lic.LicenseStatus -eq 1) { 'Activated' } else { 'Not activated' } }
} catch { }

$sys = [ordered]@{}
$sys['Computer name'] = $env:COMPUTERNAME
$sys['Manufacturer']  = $cs.Manufacturer
$sys['Model']         = $cs.Model
$sys['Serial number'] = $bios.SerialNumber
$sys['BIOS']          = '{0} ({1:yyyy-MM-dd})' -f $bios.SMBIOSBIOSVersion, $bios.ReleaseDate
$sys['Windows']       = '{0} {1} (build {2}.{3})' -f $os.Caption, $cv.DisplayVersion, $os.BuildNumber, $cv.UBR
$sys['Activation']    = $act
$sys['Installed']     = '{0:yyyy-MM-dd}' -f $os.InstallDate
$sys['Last restart']  = '{0:yyyy-MM-dd HH:mm}' -f $os.LastBootUpTime
$sys['Processor']     = '{0} ({1} cores / {2} threads)' -f $cpu.Name.Trim(), $cpu.NumberOfCores, $cpu.NumberOfLogicalProcessors
$sys['Memory']        = '{0:N1} GB' -f ($cs.TotalPhysicalMemory / 1GB)
$sys['Graphics']      = (@(Get-CimInstance Win32_VideoController | ForEach-Object { $_.Name }) -join '; ')

$ram = Get-CimInstance Win32_PhysicalMemory -ErrorAction SilentlyContinue | ForEach-Object {
    [pscustomobject]@{ Slot = $_.DeviceLocator; Size = ('{0:N0} GB' -f ($_.Capacity / 1GB)); Speed = ('{0} MT/s' -f $_.Speed); Maker = $_.Manufacturer; Part = ([string]$_.PartNumber).Trim() }
}
$pdisks = Get-PhysicalDisk -ErrorAction SilentlyContinue | ForEach-Object {
    [pscustomobject]@{ Drive = $_.FriendlyName; Type = $_.MediaType; Bus = $_.BusType; Size = ('{0:N0} GB' -f ($_.Size / 1GB)); Health = $_.HealthStatus }
}
$vols = [System.IO.DriveInfo]::GetDrives() | Where-Object { $_.IsReady -and $_.DriveType -eq 'Fixed' } | ForEach-Object {
    [pscustomobject]@{ Volume = $_.Name; Label = $_.VolumeLabel; Format = $_.DriveFormat; Size = ('{0:N0} GB' -f ($_.TotalSize / 1GB)); Free = ('{0:N1} GB ({1:N0}%)' -f ($_.AvailableFreeSpace / 1GB), ($_.AvailableFreeSpace / $_.TotalSize * 100)) }
}

$Sync.Status = 'Collecting network and security...'
$nets = Get-NetAdapter -Physical -ErrorAction SilentlyContinue | Where-Object Status -eq 'Up' | ForEach-Object {
    $ip = (Get-NetIPAddress -InterfaceIndex $_.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue | Select-Object -First 1).IPAddress
    [pscustomobject]@{ Adapter = $_.Name; Device = $_.InterfaceDescription; Speed = $_.LinkSpeed; MAC = $_.MacAddress; IPv4 = $ip }
}
$sec = [ordered]@{}
try {
    $mp = Get-MpComputerStatus -ErrorAction Stop
    $sec['Microsoft Defender'] = 'Mode: {0}; real-time: {1}; definitions {2} day(s) old' -f $mp.AMRunningMode, $mp.RealTimeProtectionEnabled, $mp.AntivirusSignatureAge
} catch { }
$av = @(Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntiVirusProduct -ErrorAction SilentlyContinue)
if ($av.Count) { $sec['Antivirus products'] = (($av | Select-Object -ExpandProperty displayName) -join ', ') }
try { $sec['Firewall'] = ((Get-NetFirewallProfile -ErrorAction Stop | ForEach-Object { '{0}: {1}' -f $_.Name, $(if ([string]$_.Enabled -eq 'False') { 'Off' } else { 'On' }) }) -join '; ') } catch { }
try { $bl = Get-BitLockerVolume -MountPoint $env:SystemDrive -ErrorAction Stop; $sec['BitLocker (system drive)'] = '{0}' -f $bl.ProtectionStatus } catch { }
try {
    $bs = Get-CimInstance -Namespace root\wmi -ClassName BatteryStaticData -ErrorAction Stop | Select-Object -First 1
    $bf = Get-CimInstance -Namespace root\wmi -ClassName BatteryFullChargedCapacity -ErrorAction Stop | Select-Object -First 1
    if ($bs.DesignedCapacity -gt 0) { $sec['Battery health'] = '{0:N0}% of original capacity' -f ($bf.FullChargedCapacity / $bs.DesignedCapacity * 100) }
} catch { }

$Sync.Status = 'Collecting devices and software...'
$problems = Get-PnpDevice -PresentOnly -Status ERROR, DEGRADED -ErrorAction SilentlyContinue | ForEach-Object {
    [pscustomobject]@{ Device = $_.FriendlyName; Class = $_.Class; Status = $_.Status }
}
$printers = Get-CimInstance Win32_Printer -ErrorAction SilentlyContinue | ForEach-Object {
    [pscustomobject]@{ Printer = $_.Name; Driver = $_.DriverName; Port = $_.PortName; Default = $(if ($_.Default) { 'Yes' } else { '' }) }
}
$startup = Get-CimInstance Win32_StartupCommand -ErrorAction SilentlyContinue | ForEach-Object {
    [pscustomobject]@{ Name = $_.Name; Command = $_.Command; Location = $_.Location }
}
$updates = Get-HotFix -ErrorAction SilentlyContinue | Where-Object InstalledOn | Sort-Object InstalledOn -Descending | Select-Object -First 10 | ForEach-Object {
    [pscustomobject]@{ Update = $_.HotFixID; Type = $_.Description; Installed = ('{0:yyyy-MM-dd}' -f $_.InstalledOn) }
}
$apps = @()
if ($IncludeApps) {
    $keys = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*',
            'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*',
            'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*'
    $apps = Get-ItemProperty $keys -ErrorAction SilentlyContinue |
        Where-Object { $_.DisplayName -and -not $_.SystemComponent -and -not $_.ParentKeyName } |
        ForEach-Object { [pscustomobject]@{ Program = $_.DisplayName; Version = $_.DisplayVersion; Publisher = $_.Publisher } } |
        Sort-Object Program -Unique
}

$Sync.Status = 'Writing report...'
$title   = if ($Info.CompanyName) { $Info.CompanyName } else { 'Service Report' }
$web     = [string]$Info.Website
$tech    = [string]$Info.Tech
$cbits = @(); if ($Info.CompanyPhone) { $cbits += ('Questions? Call ' + (HtmlEnc $Info.CompanyPhone)) }; if ($web) { $cbits += (Web-Link $web) }
$contactHtml = ($cbits -join '    |    ')
$preparedBy = if ($tech) { 'Prepared by ' + $tech } else { 'Prepared' }
$footHtml = (@((HtmlEnc $title), (Web-Link $web), (HtmlEnc $Info.CompanyPhone)) | Where-Object { $_ }) -join ' - '
$job = [ordered]@{}
if ($Info.Customer) { $job['Customer'] = $Info.Customer }
if ($Info.Ticket)   { $job['Ticket / job #'] = $Info.Ticket }
$job['Date'] = '{0:yyyy-MM-dd HH:mm}' -f (Get-Date)
if ($Info.Tech)     { $job['Technician'] = $Info.Tech }
$job['Computer'] = '{0} - {1} {2}' -f $env:COMPUTERNAME, $cs.Manufacturer, $cs.Model

$body = New-Object System.Text.StringBuilder
[void]$body.Append((Section 'Job details' (Get-HtmlKV $job)))
if ($Info.Notes) { [void]$body.Append((Section 'Technician notes' ('<p class="notes">' + ((HtmlEnc $Info.Notes) -replace "`r?`n", '<br>') + '</p>'))) }
if ($IncludeWork) {
    $work = @($Sync.WorkDone.ToArray())
    [void]$body.Append((Section 'Work performed' (Get-HtmlTable $work @('Time', 'Task', 'Result'))))
}
if ($SpeedTests -and @($SpeedTests).Count) {
    [void]$body.Append((Section 'Internet speed tests' (Get-HtmlTable @($SpeedTests) @('Time', 'Label', 'Download', 'Upload', 'Ping'))))
}
if ($BackupRecord -and @($BackupRecord).Count) {
    [void]$body.Append((Section 'Data backup' (Get-HtmlTable @($BackupRecord) @('Time', 'Source', 'Destination', 'Result'))))
}
if ($IncludeFindings -and $Findings) {
    $fs = @($Findings | Where-Object { $_.Severity -ne 'OK' })
    [void]$body.Append((Section 'Health check findings' (Get-HtmlTable $fs @('Severity', 'Area', 'Finding'))))
}
if ($RemoteScan) {
    $rsBody = '<p class="muted">Remote-access and screen-sharing software found on this PC. Confirm with the customer that each one is expected - anything unfamiliar can let an outsider control the machine and should be removed.</p>'
    $rsBody += (Get-HtmlTable @($RemoteScan) @('Severity', 'Name', 'Evidence', 'Detail'))
    [void]$body.Append((Section 'Remote-access software' $rsBody))
}
[void]$body.Append((Section 'System' (Get-HtmlKV $sys)))
[void]$body.Append((Section 'Memory modules' (Get-HtmlTable $ram @('Slot', 'Size', 'Speed', 'Maker', 'Part'))))
[void]$body.Append((Section 'Drives' ((Get-HtmlTable $pdisks @('Drive', 'Type', 'Bus', 'Size', 'Health')) + (Get-HtmlTable $vols @('Volume', 'Label', 'Format', 'Size', 'Free')))))
[void]$body.Append((Section 'Security' (Get-HtmlKV $sec)))
[void]$body.Append((Section 'Network' (Get-HtmlTable $nets @('Adapter', 'Device', 'Speed', 'MAC', 'IPv4'))))
[void]$body.Append((Section 'Devices with problems' (Get-HtmlTable $problems @('Device', 'Class', 'Status'))))
[void]$body.Append((Section 'Printers' (Get-HtmlTable $printers @('Printer', 'Driver', 'Port', 'Default'))))
[void]$body.Append((Section 'Startup programs' (Get-HtmlTable $startup @('Name', 'Command', 'Location'))))
[void]$body.Append((Section 'Recent Windows updates' (Get-HtmlTable $updates @('Update', 'Type', 'Installed'))))
if ($IncludeApps) { [void]$body.Append((Section ('Installed programs ({0})' -f @($apps).Count) (Get-HtmlTable $apps @('Program', 'Version', 'Publisher')))) }

$css = @"
body{font-family:'Segoe UI',Arial,sans-serif;margin:0;background:#f4f5f7;color:#1f2328}
header{background:#1f3a5f;color:#fff;padding:22px 32px}
header h1{margin:0;font-size:24px} header p{margin:4px 0 0;opacity:.85}
header a{color:#cfe3ff} footer a{color:#2d6cdf} a{color:#2d6cdf}
main{max-width:1000px;margin:0 auto;padding:16px}
section{background:#fff;border-radius:8px;padding:14px 18px;margin:14px 0;box-shadow:0 1px 3px rgba(0,0,0,.08)}
h2{font-size:17px;margin:0 0 10px;color:#1f3a5f}
table{border-collapse:collapse;width:100%;font-size:13px;margin-bottom:8px}
th,td{text-align:left;padding:6px 8px;border-bottom:1px solid #e5e7eb;vertical-align:top;word-break:break-word}
th{background:#f0f3f7;font-weight:600} table.kv th{width:210px}
tr.sev-critical td{color:#b42318;font-weight:600} tr.sev-warning td{color:#b54708}
.muted{color:#6b7280} .notes{white-space:normal;line-height:1.5}
footer{text-align:center;color:#6b7280;font-size:12px;padding:20px}
@media print{body{background:#fff} section{box-shadow:none;border:1px solid #ddd;break-inside:avoid}}
"@
$html = @"
<!DOCTYPE html><html><head><meta charset="utf-8"><title>$(if ($Info.ReportName) { (HtmlEnc $Info.ReportName) + ' - ' })$(HtmlEnc $title) - $(HtmlEnc $env:COMPUTERNAME)</title><style>$css</style></head>
<body><header>$(if ($Logo) { "<img src='$Logo' alt='' style='max-height:50px;margin-bottom:8px;display:block'>" })<h1>$(HtmlEnc $title)</h1><p>$(if ($Info.ReportName) { (HtmlEnc $Info.ReportName) + ' - ' })Computer service report - $(HtmlEnc $env:COMPUTERNAME)</p><p>$contactHtml</p><p>$(HtmlEnc $preparedBy) on $(Get-Date -Format 'yyyy-MM-dd HH:mm')</p></header>
<main>$($body.ToString())</main><footer>$footHtml &bull; $(HtmlEnc $preparedBy) on $(Get-Date -Format 'yyyy-MM-dd HH:mm')</footer></body></html>
"@
$ticketTag = if ($Info.Ticket) { ($Info.Ticket -replace '[^\w\-]', '') + '_' } else { '' }
$nameTag = ''
if ($Info.ReportName) {
    $n = (($Info.ReportName -replace '[^\w\- ]', '').Trim() -replace '\s+', '-')
    if ($n.Length -gt 48) { $n = $n.Substring(0, 48) }
    if ($n) { $nameTag = $n + '_' }
}
$path = Join-Path $ReportDir ('{0}{1}{2}_{3:yyyyMMdd-HHmm}.html' -f $nameTag, $ticketTag, $env:COMPUTERNAME, (Get-Date))
Set-Content -LiteralPath $path -Value $html -Encoding UTF8
$Sync.ReportPath = $path
Write-Log ('Report saved: {0}' -f $path) 'DONE'
# Drop a copy into the PCRT watched folder, named with the ticket number so PCRT can attach it.
if ($PcrtFolder) {
    try {
        if (-not (Test-Path -LiteralPath $PcrtFolder)) { New-Item -ItemType Directory -Path $PcrtFolder -Force | Out-Null }
        $pcrtName = if ($Info.Ticket) { 'd7report-{0}.html' -f ($Info.Ticket -replace '[^\w\-]', '') } else { '{0}_{1:yyyyMMddHHmm}.html' -f $env:COMPUTERNAME, (Get-Date) }
        $pcrtPath = Join-Path $PcrtFolder $pcrtName
        Copy-Item -LiteralPath $path -Destination $pcrtPath -Force
        Write-Log ('Copied to PCRT folder: {0}' -f $pcrtPath) 'OK'
    } catch { Write-Log ('Could not copy to PCRT folder: {0}' -f $_.Exception.Message) 'WARN' }
}
'@

$RemoteScanScript = @'
$tools = @(
    @{ N = 'TeamViewer'; Rx = 'teamviewer' }
    @{ N = 'AnyDesk'; Rx = 'anydesk' }
    @{ N = 'ScreenConnect / ConnectWise Control'; Rx = 'screenconnect|connectwise control|connectwisecontrol' }
    @{ N = 'RustDesk'; Rx = 'rustdesk' }
    @{ N = 'UltraViewer'; Rx = 'ultraviewer' }
    @{ N = 'UltraVNC'; Rx = 'ultravnc' }
    @{ N = 'TightVNC'; Rx = 'tightvnc' }
    @{ N = 'RealVNC'; Rx = 'realvnc|vnc server|vncserver|winvnc' }
    @{ N = 'LogMeIn'; Rx = 'logmein' }
    @{ N = 'GoToMyPC / GoToAssist'; Rx = 'gotomypc|gotoassist' }
    @{ N = 'Splashtop'; Rx = 'splashtop' }
    @{ N = 'Chrome Remote Desktop'; Rx = 'chrome[ _]remote[ _]desktop|chromoting|remoting_host' }
    @{ N = 'Quick Assist'; Rx = 'quickassist' }
    @{ N = 'Windows Remote Assistance'; Rx = '\bmsra\b' }
    @{ N = 'Supremo'; Rx = 'supremo' }
    @{ N = 'Ammyy Admin'; Rx = 'ammyy' }
    @{ N = 'AeroAdmin'; Rx = 'aeroadmin' }
    @{ N = 'AweSun / AweRay'; Rx = 'awesun|aweray' }
    @{ N = 'DWService / DWAgent'; Rx = 'dwservice|dwagent' }
    @{ N = 'Zoho Assist'; Rx = 'zoho assist|zohods' }
    @{ N = 'Remote Utilities'; Rx = 'remote utilities|rutserv|rfusclient' }
    @{ N = 'NoMachine'; Rx = 'nomachine' }
    @{ N = 'Parsec'; Rx = 'parsecd|\bparsec\b' }
    @{ N = 'Dameware'; Rx = 'dameware' }
    @{ N = 'BeyondTrust / Bomgar'; Rx = 'bomgar|beyondtrust' }
    @{ N = 'Atera'; Rx = 'ateraagent|atera agent' }
    @{ N = 'Syncro / SyncroMSP'; Rx = 'syncromsp|\bsyncro\b' }
    @{ N = 'Action1'; Rx = 'action1' }
    @{ N = 'Pulseway'; Rx = 'pulseway' }
    @{ N = 'N-able Take Control'; Rx = 'n-able|take control|basupsrvc' }
)
$results = New-Object System.Collections.ArrayList
function Add-RS($Name, $Evidence, $Detail) {
    [void]$results.Add([pscustomobject]@{ Severity = 'Review'; Name = $Name; Evidence = $Evidence; Detail = $Detail })
    Write-Log ('{0} - {1}: {2}' -f $Name, $Evidence, $Detail) 'WARN'
}
# Read a registry key's last-write time = when a program's uninstall entry was written (install/update moment).
if (-not ('BK.Reg' -as [type])) {
    try {
        Add-Type -Namespace BK -Name Reg -MemberDefinition @"
[System.Runtime.InteropServices.DllImport("advapi32.dll")]
public static extern int RegQueryInfoKey(Microsoft.Win32.SafeHandles.SafeRegistryHandle hKey, System.IntPtr lpClass, System.IntPtr lpcchClass, System.IntPtr lpReserved, System.IntPtr lpcSubKeys, System.IntPtr lpcbMaxSubKeyLen, System.IntPtr lpcbMaxClassLen, System.IntPtr lpcValues, System.IntPtr lpcbMaxValueNameLen, System.IntPtr lpcbMaxValueLen, System.IntPtr lpcbSecurityDescriptor, out long lpftLastWriteTime);
"@ -ErrorAction Stop
    } catch { }
}
function Get-KeyWriteTime($key) {
    try {
        $ft = [long]0
        if ([BK.Reg]::RegQueryInfoKey($key.Handle, [IntPtr]::Zero, [IntPtr]::Zero, [IntPtr]::Zero, [IntPtr]::Zero, [IntPtr]::Zero, [IntPtr]::Zero, [IntPtr]::Zero, [IntPtr]::Zero, [IntPtr]::Zero, [IntPtr]::Zero, [ref]$ft) -eq 0) { return [DateTime]::FromFileTime($ft) }
    } catch { }
    return $null
}
Write-Log 'Scanning for remote-access and screen-sharing software...' 'STEP'

$Sync.Status = 'Checking installed programs...'
$uninstRoots = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall', 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall', 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'
foreach ($root in $uninstRoots) {
    foreach ($sk in (Get-ChildItem -LiteralPath $root -ErrorAction SilentlyContinue)) {
        $dn = [string]$sk.GetValue('DisplayName'); if (-not $dn) { continue }
        foreach ($t in $tools) {
            if ($dn -match $t.Rx) {
                $ver = [string]$sk.GetValue('DisplayVersion')
                $wt = Get-KeyWriteTime $sk
                $whenTxt = ''
                if ($wt) { $whenTxt = '  - installed/updated ' + $wt.ToString('yyyy-MM-dd HH:mm') }
                else { $idr = [string]$sk.GetValue('InstallDate'); if ($idr -match '^\d{8}$') { try { $whenTxt = '  - installed ' + ([datetime]::ParseExact($idr, 'yyyyMMdd', $null)).ToString('yyyy-MM-dd') } catch { } } }
                Add-RS $t.N 'Installed program' ((('{0} {1}' -f $dn, $ver).Trim()) + $whenTxt)
                break
            }
        }
    }
}

$Sync.Status = 'Checking running processes...'
$procs = @(Get-Process -ErrorAction SilentlyContinue)
foreach ($t in $tools) { foreach ($pr in $procs) { $hay = ('{0} {1} {2}' -f $pr.ProcessName, $pr.Path, $pr.Description); if ($hay -match $t.Rx) { Add-RS $t.N 'Running process' ('{0} (PID {1})' -f $pr.ProcessName, $pr.Id) } } }

$Sync.Status = 'Checking services...'
$svcs = @(Get-CimInstance Win32_Service -ErrorAction SilentlyContinue)
foreach ($t in $tools) { foreach ($s in $svcs) { $hay = ('{0} {1} {2}' -f $s.Name, $s.DisplayName, $s.PathName); if ($hay -match $t.Rx) { Add-RS $t.N 'Service' ('{0} [{1}/{2}]' -f $s.DisplayName, $s.State, $s.StartMode) } } }

$Sync.Status = 'Checking scheduled tasks...'
try {
    $tasks = @(Get-ScheduledTask -ErrorAction Stop)
    foreach ($t in $tools) { foreach ($tk in $tasks) {
        $acts = ($tk.Actions | ForEach-Object { '{0} {1}' -f $_.Execute, $_.Arguments }) -join ' '
        $hay = ('{0} {1}' -f $tk.TaskName, $acts)
        if ($hay -match $t.Rx) { Add-RS $t.N 'Scheduled task' ('{0}{1}' -f $tk.TaskPath, $tk.TaskName) }
    } }
} catch { }

$final = @($results | Sort-Object Name, Evidence, Detail -Unique)
$Sync.RemoteScan = $final
if ($final.Count) { Write-Log ('Remote-access scan: {0} item(s) found. Confirm each one with the customer - anything unexpected can let an outsider in.' -f $final.Count) 'DONE' }
else { Write-Log 'Remote-access scan: nothing found.' 'DONE' }
'@

$InfoRecoveryScript = @'
function HtmlEnc($v) { [System.Net.WebUtility]::HtmlEncode([string]$v) }
$rows = New-Object System.Collections.ArrayList
function Add-Row($Cat, $Item, $Value) { [void]$rows.Add([pscustomobject]@{ Cat = $Cat; Item = $Item; Value = $Value }) }
Write-Log 'Recovering customer information...' 'STEP'

if ($Recover -contains 'productkey') {
    $Sync.Status = 'Reading product key...'
    $oem = $null; try { $oem = (Get-CimInstance -ClassName SoftwareLicensingService -ErrorAction Stop).OA3xOriginalProductKey } catch { }
    if ($oem) { Add-Row 'Windows' 'OEM product key (in firmware)' $oem; Write-Log 'Windows OEM product key recovered (saved to sheet).' 'OK' }
    else { Add-Row 'Windows' 'Product key' 'No embedded OEM key - this PC uses a retail or digital license tied to the Microsoft account / hardware, so there is no key to write down.'; Write-Log 'No embedded OEM product key (digital/retail license).' }
    Add-Row 'Windows' 'Edition' ((Get-CimInstance Win32_OperatingSystem).Caption)
}

if ($Recover -contains 'wifi') {
    $Sync.Status = 'Reading saved Wi-Fi networks...'
    $profiles = @()
    (netsh wlan show profiles) 2>&1 | Select-String 'All User Profile\s*:\s*(.+)$' | ForEach-Object { $profiles += $_.Matches[0].Groups[1].Value.Trim() }
    if (-not $profiles.Count) { Write-Log 'No saved Wi-Fi profiles found (or no wireless adapter).' }
    foreach ($p in $profiles) {
        $key = ''
        (netsh wlan show profile name="$p" key=clear) 2>&1 | Select-String 'Key Content\s*:\s*(.+)$' | ForEach-Object { $key = $_.Matches[0].Groups[1].Value.Trim() }
        Add-Row 'Wi-Fi' $p $(if ($key) { $key } else { '(open network or password not stored)' })
        Write-Log ('Wi-Fi "{0}": {1}' -f $p, $(if ($key) { 'password saved to sheet' } else { 'no key' })) 'OK'
    }
}

if ($Recover -contains 'bitlocker') {
    if (-not $BitlockerConsent) {
        Add-Row 'BitLocker' 'Status' 'Not checked - the customer-consent box on the Info / Recovery tab was not ticked.'
        Write-Log 'BitLocker skipped: the customer-consent box was not ticked.' 'WARN'
    }
    else {
        $Sync.Status = 'Reading BitLocker status and recovery keys...'
        $usedCmdlet = $false; $reported = $false
        if (Get-Command Get-BitLockerVolume -ErrorAction SilentlyContinue) {
            $usedCmdlet = $true
            $vols = @(); try { $vols = @(Get-BitLockerVolume -ErrorAction Stop) } catch { Write-Log ('Get-BitLockerVolume failed, trying manage-bde: {0}' -f $_.Exception.Message) 'WARN'; $usedCmdlet = $false }
            if ($usedCmdlet) {
                foreach ($v in $vols) {
                    $reported = $true
                    $on = ("$($v.ProtectionStatus)" -eq 'On' -or "$($v.ProtectionStatus)" -eq '1')
                    if ($on) {
                        $rp = @($v.KeyProtector | Where-Object { $_.KeyProtectorType -eq 'RecoveryPassword' -and $_.RecoveryPassword })
                        if ($rp.Count) {
                            foreach ($k in $rp) { Add-Row 'BitLocker' ('Drive {0} - recovery key' -f $v.MountPoint) $k.RecoveryPassword; Write-Log ('BitLocker recovery key for {0} saved to sheet.' -f $v.MountPoint) 'OK' }
                        }
                        else {
                            Add-Row 'BitLocker' ('Drive {0}' -f $v.MountPoint) 'Encrypted (BitLocker on), but no numeric recovery-password protector is stored on this volume.'
                            Write-Log ('{0}: protected, no recovery-password protector.' -f $v.MountPoint) 'WARN'
                        }
                    }
                    else {
                        Add-Row 'BitLocker' ('Drive {0}' -f $v.MountPoint) 'Not encrypted (BitLocker is off) - no recovery key.'
                        Write-Log ('{0}: BitLocker is off (not encrypted).' -f $v.MountPoint) 'OK'
                    }
                }
            }
        }
        if (-not $usedCmdlet) {
            # Fallback for Windows editions without the BitLocker PowerShell module: parse manage-bde output.
            Write-Log 'Reading BitLocker via manage-bde...'
            $mbde = Join-Path $env:SystemRoot 'System32\manage-bde.exe'
            foreach ($dl in @(Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3' -ErrorAction SilentlyContinue | ForEach-Object { $_.DeviceID })) {
                $reported = $true
                $out = (& $mbde -protectors -get $dl 2>&1 | Out-String)
                $status = (& $mbde -status $dl 2>&1 | Out-String)
                $keys = [regex]::Matches($out, '([0-9]{6}-[0-9]{6}-[0-9]{6}-[0-9]{6}-[0-9]{6}-[0-9]{6}-[0-9]{6}-[0-9]{6})')
                if ($keys.Count) {
                    foreach ($mm in $keys) { Add-Row 'BitLocker' ('Drive {0} - recovery key' -f $dl) $mm.Groups[1].Value; Write-Log ('BitLocker recovery key for {0} saved to sheet.' -f $dl) 'OK' }
                }
                elseif ($status -match 'Protection Status:\s*Protection On') {
                    Add-Row 'BitLocker' ('Drive {0}' -f $dl) 'Encrypted (BitLocker on), but no numeric recovery-password protector is stored on this volume.'
                    Write-Log ('{0}: protected, no recovery-password protector.' -f $dl) 'WARN'
                }
                else {
                    Add-Row 'BitLocker' ('Drive {0}' -f $dl) 'Not encrypted (BitLocker is off) - no recovery key.'
                    Write-Log ('{0}: BitLocker is off (not encrypted).' -f $dl) 'OK'
                }
            }
        }
        if (-not $reported) {
            Add-Row 'BitLocker' 'Status' 'No fixed drives were found to check.'
            Write-Log 'BitLocker: no fixed drives found to check.' 'WARN'
        }
    }
}

$title = if ($Info.CompanyName) { $Info.CompanyName } else { 'Customer Information Sheet' }
$web = [string]$Info.Website
$webLink = Web-Link $web
$tech = [string]$Info.Tech
$preparedBy = if ($tech) { 'Prepared by ' + $tech } else { 'Prepared' }
$footHtml = (@((HtmlEnc $title), (Web-Link $web), (HtmlEnc $Info.CompanyPhone)) | Where-Object { $_ }) -join ' - '
$meta = [ordered]@{}
if ($Info.Customer) { $meta['Customer'] = $Info.Customer }
if ($Info.Ticket)   { $meta['Ticket / job #'] = $Info.Ticket }
$meta['Computer'] = $env:COMPUTERNAME
$meta['Prepared'] = ('{0:yyyy-MM-dd HH:mm}' -f (Get-Date))
if ($Info.Tech)     { $meta['Technician'] = $Info.Tech }
$metaHtml = '<table class="kv">'; foreach ($k in $meta.Keys) { $metaHtml += ('<tr><th>{0}</th><td>{1}</td></tr>' -f (HtmlEnc $k), (HtmlEnc $meta[$k])) }; $metaHtml += '</table>'
$tbl = '<table><tr><th>Category</th><th>Item</th><th>Value</th></tr>'
foreach ($r in $rows) { $tbl += ('<tr><td>{0}</td><td>{1}</td><td class="val">{2}</td></tr>' -f (HtmlEnc $r.Cat), (HtmlEnc $r.Item), (HtmlEnc $r.Value)) }
$tbl += '</table>'
if (-not $rows.Count) { $tbl = '<p>Nothing was selected to recover.</p>' }
$css = @"
body{font-family:'Segoe UI',Arial,sans-serif;margin:0;background:#f4f5f7;color:#1f2328}
header{background:#5f1f3a;color:#fff;padding:20px 28px}h1{margin:0;font-size:22px}
header a{color:#ffd6ea} footer a{color:#2d6cdf} a{color:#2d6cdf}
main{max-width:860px;margin:0 auto;padding:16px}
section{background:#fff;border-radius:8px;padding:14px 18px;margin:14px 0;box-shadow:0 1px 3px rgba(0,0,0,.08)}
table{border-collapse:collapse;width:100%;font-size:13px}th,td{text-align:left;padding:7px 9px;border-bottom:1px solid #e5e7eb}
th{background:#f0f3f7}table.kv th{width:200px}.val{font-family:Consolas,monospace}
.warn{background:#fff6e5;border:1px solid #f0c36d;border-radius:8px;padding:10px 14px;margin:14px 0;font-size:13px}
footer{text-align:center;color:#6b7280;font-size:12px;padding:18px}
"@
$warn = '<div class="warn"><b>Confidential.</b> This sheet holds the customer''s own recovery information (Wi-Fi passwords, product key, BitLocker recovery key). Store it securely with the customer''s consent and hand it over or delete it per your shop''s data policy.</div>'
$html = @"
<!DOCTYPE html><html><head><meta charset="utf-8"><title>$(HtmlEnc $title) - $(HtmlEnc $env:COMPUTERNAME)</title><style>$css</style></head>
<body><header>$(if ($Logo) { "<img src='$Logo' alt='' style='max-height:50px;margin-bottom:8px;display:block'>" })<h1>$(HtmlEnc $title)</h1><p>Customer information sheet$(if ($webLink) { ' - ' + $webLink })</p><p>$(HtmlEnc $preparedBy) on $(Get-Date -Format 'yyyy-MM-dd HH:mm')</p></header><main>$warn<section>$metaHtml</section><section>$tbl</section></main>
<footer>$footHtml &bull; $(HtmlEnc $preparedBy) on $(Get-Date -Format 'yyyy-MM-dd HH:mm') - keep confidential</footer></body></html>
"@
$ticketTag = if ($Info.Ticket) { ($Info.Ticket -replace '[^\w\-]', '') + '_' } else { '' }
$path = Join-Path $ReportDir ('info_{0}{1}_{2:yyyyMMdd-HHmm}.html' -f $ticketTag, $env:COMPUTERNAME, (Get-Date))
Set-Content -LiteralPath $path -Value $html -Encoding UTF8
$Sync.InfoSheetPath = $path
Write-Log ('Customer info sheet saved: {0}' -f $path) 'DONE'
'@

# ---- App updates (Fixyfier-style): list and update third-party apps via winget ----------------
$AppUpdateScanScript = @'
$wg = Get-WingetPath
if (-not $wg) { Write-Log 'winget is not available on this PC. Install "App Installer" from the Microsoft Store, then try again.' 'ERROR'; $Sync.AppUpdates = @(); return }
Write-Log 'Checking installed apps for available updates (winget)...' 'STEP'
$raw = (& $wg upgrade --include-unknown --accept-source-agreements 2>&1 | Out-String)
foreach ($ln in ($raw -split "`r?`n")) { if ($ln.Trim()) { Write-Log $ln 'OUT' } }
$list = New-Object System.Collections.ArrayList
$lines = $raw -split "`r?`n"
$hdr = -1
for ($i = 0; $i -lt $lines.Count; $i++) { if ($lines[$i] -match '^\s*Name\s+Id\s+Version\s+Available') { $hdr = $i; break } }
if ($hdr -ge 0) {
    $h = $lines[$hdr]
    $cId = $h.IndexOf('Id'); $cVer = $h.IndexOf('Version'); $cAvail = $h.IndexOf('Available'); $cSrc = $h.IndexOf('Source')
    function Slice([string]$s, [int]$a, [int]$b) {
        if ($a -lt 0 -or $a -ge $s.Length) { return '' }
        if ($b -lt 0 -or $b -gt $s.Length) { $b = $s.Length }
        if ($b -le $a) { return '' }
        return $s.Substring($a, $b - $a).Trim()
    }
    for ($i = $hdr + 2; $i -lt $lines.Count; $i++) {
        $ln = $lines[$i]
        if ($ln.Trim() -eq '') { continue }
        if ($ln -match '^-{5,}') { continue }
        if ($ln -match 'upgrades? available|require explicit targeting|following packages|^\s*No ') { continue }
        $name = Slice $ln 0 $cId
        $id   = Slice $ln $cId $cVer
        $cur  = Slice $ln $cVer $cAvail
        $av   = if ($cSrc -gt 0) { Slice $ln $cAvail $cSrc } else { Slice $ln $cAvail $ln.Length }
        if ($id -and $id -notmatch '\s') { [void]$list.Add([pscustomobject]@{ Name = $name; Id = $id; Current = $cur; Available = $av }) }
    }
}
$Sync.AppUpdates = @($list)
Write-Log ('Update check complete - {0} app update(s) available.' -f @($list).Count) 'DONE'
'@

$AppUpdateRunScript = @'
$wg = Get-WingetPath
if (-not $wg) { Write-Log 'winget is not available on this PC.' 'ERROR'; return }
$updated = @()
if ($All) {
    Write-Log 'Updating every app that has an update available (winget)...' 'STEP'
    Invoke-Exe $wg @('upgrade', '--all', '--include-unknown', '--silent', '--accept-package-agreements', '--accept-source-agreements') | Out-Null
    $updated = @($Targets)
    Write-Log 'Finished updating all apps.' 'DONE'
}
else {
    $n = @($Ids).Count; $i = 0
    foreach ($id in $Ids) {
        $i++
        if ($Sync.Cancel) { Write-Log 'Stopped by technician.' 'WARN'; break }
        $Sync.Status = ('Updating {0} ({1}/{2})...' -f $id, $i, $n)
        Write-Log ('Updating {0}  ({1} of {2})' -f $id, $i, $n) 'STEP'
        Invoke-Exe $wg @('upgrade', '--id', $id, '-e', '--include-unknown', '--silent', '--accept-package-agreements', '--accept-source-agreements') | Out-Null
        $t = @($Targets | Where-Object { $_.Id -eq $id }) | Select-Object -First 1
        if ($t) { $updated += $t } else { $updated += [pscustomobject]@{ Name = $id; Id = $id; Current = ''; Available = '' } }
    }
    Write-Log ('Finished - updated {0} app(s).' -f @($updated).Count) 'DONE'
}
# Track each updated app (name + old -> new version) for the Before/After report.
foreach ($u in @($updated)) {
    [void]$Sync.AppsUpdated.Add([pscustomobject]@{ Time = (Get-Date).ToString('yyyy-MM-dd HH:mm'); Name = [string]$u.Name; From = [string]$u.Current; To = [string]$u.Available })
}
if (@($updated).Count) {
    $names = (@($updated | ForEach-Object { $_.Name }) -join ', ')
    [void]$Sync.WorkDone.Add([pscustomobject]@{ Time = (Get-Date).ToString('yyyy-MM-dd HH:mm'); Task = 'App updates'; Result = ('Updated ' + $names); Seconds = 0 })
}
'@

# ---- Before/After snapshot: health + a light performance score, to show cleanup results -----
$SnapshotScript = @'
Write-Log ('Capturing {0} snapshot...' -f $Slot) 'STEP'
$sys = $env:SystemDrive
$d = Get-CimInstance Win32_LogicalDisk -Filter ("DeviceID='{0}'" -f $sys) -ErrorAction SilentlyContinue
$freeGB = if ($d) { [math]::Round($d.FreeSpace / 1GB, 1) } else { 0 }
$totGB  = if ($d -and $d.Size) { [math]::Round($d.Size / 1GB, 1) } else { 0 }
$freePct = if ($d -and $d.Size) { [math]::Round(($d.FreeSpace / $d.Size) * 100) } else { 0 }

$os = Get-CimInstance Win32_OperatingSystem -ErrorAction SilentlyContinue
$memTotGB = if ($os) { [math]::Round($os.TotalVisibleMemorySize / 1MB, 1) } else { 0 }
$memUsedPct = if ($os -and $os.TotalVisibleMemorySize) { [math]::Round((($os.TotalVisibleMemorySize - $os.FreePhysicalMemory) / $os.TotalVisibleMemorySize) * 100) } else { 0 }

$Sync.Status = 'Counting processes and startup items...'
$proc = @(Get-Process -ErrorAction SilentlyContinue).Count
$startup = @(Get-CimInstance Win32_StartupCommand -ErrorAction SilentlyContinue).Count

$Sync.Status = 'Measuring temporary / junk files...'
$tempMB = 0
foreach ($t in @($env:TEMP, (Join-Path $env:SystemRoot 'Temp'))) {
    if ($t -and (Test-Path -LiteralPath $t)) {
        try { $s = (Get-ChildItem -LiteralPath $t -Recurse -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum).Sum; if ($s) { $tempMB += $s / 1MB } } catch { }
    }
}
$tempMB = [math]::Round($tempMB)

$Sync.Status = 'Running a quick CPU performance check...'
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$acc = 0.0; for ($i = 1; $i -lt 3000000; $i++) { $acc += [math]::Sqrt($i) }
$sw.Stop(); $cpuSec = [math]::Round($sw.Elapsed.TotalSeconds, 2)

$Sync.Status = 'Running a quick disk speed check...'
$diskW = 0; $diskR = 0
try {
    $tmp = Join-Path $env:TEMP ('bk_bench_{0}.tmp' -f [guid]::NewGuid().ToString('N'))
    $chunk = New-Object byte[] (4MB); (New-Object System.Random).NextBytes($chunk); $chunks = 16
    $sw.Restart(); $fs = [System.IO.File]::Open($tmp, 'Create', 'Write'); for ($w = 0; $w -lt $chunks; $w++) { $fs.Write($chunk, 0, $chunk.Length) }; $fs.Flush($true); $fs.Close(); $sw.Stop()
    if ($sw.Elapsed.TotalSeconds -gt 0) { $diskW = [math]::Round(($chunks * 4) / $sw.Elapsed.TotalSeconds) }
    $sw.Restart(); $fs = [System.IO.File]::Open($tmp, 'Open', 'Read'); $rb = New-Object byte[] (4MB); while ($fs.Read($rb, 0, $rb.Length) -gt 0) { }; $fs.Close(); $sw.Stop()
    if ($sw.Elapsed.TotalSeconds -gt 0) { $diskR = [math]::Round(($chunks * 4) / $sw.Elapsed.TotalSeconds) }
    Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue
} catch { Write-Log ('Disk check skipped: {0}' -f $_.Exception.Message) 'WARN' }

$Sync.Status = 'Checking security (antivirus, firewall)...'
# Antivirus via Security Center; decode productState for enabled / up-to-date.
$avName = ''; $avEnabled = 'Unknown'; $avUp = 'Unknown'
try {
    $av = @(Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntiVirusProduct -ErrorAction Stop)
    if ($av.Count) {
        $avName = (($av | Select-Object -ExpandProperty displayName) -join ', ')
        $hex = '{0:X6}' -f [int]$av[0].productState
        $enByte = [Convert]::ToInt32($hex.Substring(2, 2), 16)
        $upByte = [Convert]::ToInt32($hex.Substring(4, 2), 16)
        $avEnabled = if ($enByte -band 0x10) { 'On' } else { 'Off' }
        $avUp = if ($upByte -eq 0) { 'Yes' } else { 'No' }
    }
} catch { }
# Defender specifics (real-time, definition age).
$rtp = 'Unknown'; $defAge = $null
try { $mp = Get-MpComputerStatus -ErrorAction Stop; $rtp = if ($mp.RealTimeProtectionEnabled) { 'On' } else { 'Off' }; $defAge = [int]$mp.AntivirusSignatureAge } catch { }
if (-not $avName -and $mp) { $avName = 'Microsoft Defender' }
if (-not $avName) { $avName = 'None detected' }
# Prefer Defender's real-time flag when Defender is the active AV; else the Security Center flag.
$isDefender = ($avName -match 'Defender')
$protection = if ($isDefender -and $rtp -ne 'Unknown') { $rtp } elseif ($avEnabled -ne 'Unknown') { $avEnabled } elseif ($rtp -ne 'Unknown') { $rtp } else { 'Unknown' }
$uptodate = if ($isDefender -and $defAge -ne $null) { if ($defAge -le 7) { 'Yes' } else { 'No' } } elseif ($avUp -ne 'Unknown') { $avUp } elseif ($defAge -ne $null) { if ($defAge -le 7) { 'Yes' } else { 'No' } } else { 'Unknown' }
# Firewall per profile.
$fw = 'Unknown'
try { $pf = Get-NetFirewallProfile -ErrorAction Stop; $offp = @($pf | Where-Object { [string]$_.Enabled -eq 'False' }); $fw = if ($offp.Count) { 'Off: ' + (($offp | ForEach-Object { $_.Name }) -join ', ') } else { 'On (all profiles)' } } catch { }

$Sync.Status = 'Checking hardware health and errors...'
# Physical disk health + SMART failure prediction.
$hwDiskHealth = 'Unknown'; $hwSmart = 0; $hwDetail = @()
try {
    $pd = @(Get-PhysicalDisk -ErrorAction Stop)
    if ($pd.Count) {
        $bad = @($pd | Where-Object { $_.HealthStatus -and "$($_.HealthStatus)" -ne 'Healthy' })
        if ($bad.Count) { $hwDiskHealth = (($bad | ForEach-Object { '{0}: {1}' -f $_.FriendlyName, $_.HealthStatus }) -join '; ') }
        else { $hwDiskHealth = 'Healthy' }
    }
} catch { }
try { $hwSmart = @(Get-CimInstance -Namespace root\wmi -ClassName MSStorageDriver_FailurePredictStatus -ErrorAction Stop | Where-Object { $_.PredictFailure }).Count } catch { }
# Hardware errors (WHEA) and disk / file-system errors. Default window = last 14 days; for an
# AFTER snapshot the UI can pass $SinceIso (the Before-snapshot time) so a fix reads as zero.
$since = (Get-Date).AddDays(-14)
$errBasis = 'last 14 days'
if ($Slot -eq 'After' -and $SinceIso) { try { $since = [datetime]$SinceIso; $errBasis = 'since the Before snapshot' } catch { } }
$hwWhea = 0
try { $hwWhea = @(Get-WinEvent -FilterHashtable @{ LogName = 'System'; ProviderName = 'Microsoft-Windows-WHEA-Logger'; StartTime = $since } -ErrorAction Stop).Count } catch { }
$hwDiskErr = 0
foreach ($pv in @('disk', 'Ntfs', 'Microsoft-Windows-Ntfs')) {
    try { $hwDiskErr += @(Get-WinEvent -FilterHashtable @{ LogName = 'System'; ProviderName = $pv; Level = @(1, 2); StartTime = $since } -ErrorAction Stop).Count } catch { }
}
# Device Manager problem devices.
$hwBadDev = 0; $hwBadDevList = ''
try {
    $pnp = @(Get-CimInstance Win32_PnPEntity -ErrorAction Stop | Where-Object { $_.ConfigManagerErrorCode -and $_.ConfigManagerErrorCode -ne 0 })
    $hwBadDev = $pnp.Count
    if ($hwBadDev) { $hwBadDevList = (($pnp | Select-Object -First 5 -ExpandProperty Name) -join '; ') }
} catch { }

$snap = [ordered]@{
    Time = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')
    FreeGB = $freeGB; TotalGB = $totGB; FreePct = $freePct
    Processes = $proc; Startup = $startup
    MemUsedPct = $memUsedPct; MemTotGB = $memTotGB; TempMB = $tempMB
    CpuSec = $cpuSec; DiskWriteMBps = $diskW; DiskReadMBps = $diskR
    SecAV = $avName; SecProtection = $protection; SecUpToDate = $uptodate; SecDefAge = $(if ($defAge -ne $null) { $defAge } else { '' }); SecFirewall = $fw
    HwDiskHealth = $hwDiskHealth; HwSmart = $hwSmart; HwBadDev = $hwBadDev; HwBadDevList = $hwBadDevList; HwWhea = $hwWhea; HwDiskErr = $hwDiskErr
    HwErrBasis = $errBasis; CapturedAt = (Get-Date)
}
if ($Slot -eq 'Before') { $Sync.SnapBefore = $snap } else { $Sync.SnapAfter = $snap }
$hwNote = if ($hwDiskHealth -ne 'Healthy' -and $hwDiskHealth -ne 'Unknown') { ' DRIVE HEALTH: ' + $hwDiskHealth + '.' } elseif ($hwSmart -gt 0) { ' SMART warns of possible drive failure.' } elseif (($hwWhea + $hwDiskErr + $hwBadDev) -gt 0) { (' Hardware/disk errors or problem devices found - check the Before/After tab.') } else { '' }
Write-Log ('{0} snapshot captured - {1}% disk free, {2} startup items, {3} MB temp, CPU {4}s.{5}' -f $Slot, $freePct, $startup, $tempMB, $cpuSec, $hwNote) $(if ($hwNote) { 'WARN' } else { 'DONE' })
'@

$DeployRemoteScript = @'
$installed = $false
if (@(Get-Service -ErrorAction SilentlyContinue | Where-Object { $_.Name -match 'screenconnect' -or $_.DisplayName -match 'screenconnect|connectwise control' }).Count) { $installed = $true }
if (@(Get-Process -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -match 'screenconnect|connectwisecontrol' }).Count) { $installed = $true }
if ($LaunchExe -and (Test-Path -LiteralPath $LaunchExe)) { $installed = $true }

if ($installed) {
    Write-Log 'Remote support agent is already present on this PC.' 'OK'
    if ($LaunchExe -and (Test-Path -LiteralPath $LaunchExe)) {
        Start-Process -FilePath $LaunchExe
        Write-Log ('Launched {0}' -f $LaunchExe) 'OK'
    } else {
        Get-Service -ErrorAction SilentlyContinue | Where-Object { $_.Name -match 'screenconnect' } | ForEach-Object {
            if ($_.Status -ne 'Running') { Start-Service $_.Name -ErrorAction SilentlyContinue; Write-Log ('Started service {0}' -f $_.Name) 'OK' }
            else { Write-Log ('Service {0} is already running - your remote tool should see this PC.' -f $_.Name) 'OK' }
        }
    }
    return
}

if (-not $Installer) { Write-Log 'No agent installed and no installer configured. Set it in Settings > Remote support.' 'ERROR'; return }
$src = $Installer
if ($Installer -match '^https?://') {
    $Sync.Status = 'Downloading remote agent...'
    $ext = [IO.Path]::GetExtension(($Installer -split '\?')[0]); if (-not $ext) { $ext = '.exe' }
    $src = Join-Path $env:TEMP ('ragent_{0}{1}' -f (Get-Date -Format 'HHmmss'), $ext)
    try { Invoke-WebRequest -Uri $Installer -OutFile $src -UseBasicParsing -ErrorAction Stop; Write-Log ('Downloaded installer to {0}' -f $src) 'OK' }
    catch { Write-Log ('Download failed: {0}' -f $_.Exception.Message) 'ERROR'; return }
} elseif (-not (Test-Path -LiteralPath $src)) { Write-Log ('Installer not found: {0}' -f $src) 'ERROR'; return }

$Sync.Status = 'Installing remote agent...'
if ($src -match '\.msi$') {
    $margs = @('/i', ('"{0}"' -f $src)); if ($InstArgs) { $margs += ($InstArgs -split ' ') } else { $margs += '/qn' }
    Invoke-Exe 'msiexec.exe' $margs | Out-Null
} else {
    Write-Log ('> {0} {1}' -f $src, $InstArgs) 'CMD'
    try {
        $p = if ($InstArgs) { Start-Process -FilePath $src -ArgumentList $InstArgs -PassThru -Wait -ErrorAction Stop } else { Start-Process -FilePath $src -PassThru -Wait -ErrorAction Stop }
        Write-Log ('Installer exit code: {0}' -f $p.ExitCode) $(if ($p.ExitCode -eq 0) { 'OK' } else { 'WARN' })
    } catch { Write-Log ('Install failed: {0}' -f $_.Exception.Message) 'ERROR'; return }
}
Write-Log 'Remote support agent deployment finished.' 'DONE'
'@

$ProfileScanScript = @'
$root = $Root
if (-not (Test-Path -LiteralPath $root)) { Write-Log ('Folder not found: {0}' -f $root) 'ERROR'; $Sync.Profiles = @(); return }
Write-Log ('Scanning user profiles under {0}...' -f $root) 'STEP'
$skip = 'Public', 'Default', 'Default User', 'All Users', 'defaultuser0', 'WDAGUtilityAccount'
$list = New-Object System.Collections.ArrayList
foreach ($d in (Get-ChildItem -LiteralPath $root -Directory -Force -ErrorAction SilentlyContinue)) {
    if ($skip -contains $d.Name) { continue }
    if ($d.Attributes -band [IO.FileAttributes]::ReparsePoint) { continue }
    $Sync.Status = ('Sizing {0}...' -f $d.Name)
    $mb = 0
    foreach ($f in 'Documents', 'Desktop', 'Pictures', 'Music', 'Videos', 'Downloads') { $mb += (Get-SizeMB (Join-Path $d.FullName $f)) }
    [void]$list.Add([pscustomobject]@{ User = $d.Name; Path = $d.FullName; DataMB = [math]::Round($mb) })
    Write-Log ('{0}: ~{1:N0} MB in common data folders' -f $d.Name, $mb) 'OK'
}
$Sync.Profiles = @($list)
Write-Log ('Found {0} profile(s).' -f $list.Count) 'DONE'
'@

$CopyJobScript = @'
$jobs = @($Jobs)
$total = $jobs.Count
$n = 0
$failed = 0
foreach ($j in $jobs) {
    if ($Sync.Cancel) { Write-Log 'Stopped by user - remaining items skipped.' 'WARN'; break }
    $n++
    $Sync.Progress = $n - 1
    $Sync.Status = ('[{0}/{1}] {2}' -f $n, $total, $j.Label)
    if (-not (Test-Path -LiteralPath $j.From)) { Write-Log ('Skip {0}: nothing at source ({1})' -f $j.Label, $j.From); continue }
    Write-Log ('=== {0} ===' -f $j.Label) 'STEP'
    try { New-Item -ItemType Directory -Path $j.To -Force -ErrorAction SilentlyContinue | Out-Null } catch { }
    Write-Log ('> robocopy "{0}" "{1}" /E /ZB /R:1 /W:1' -f $j.From, $j.To) 'CMD'
    $out = & robocopy $j.From $j.To /E /ZB /DCOPY:DAT /COPY:DAT /R:1 /W:1 /XJ /NP /NFL /NDL /NJH 2>&1
    $code = $LASTEXITCODE
    $out | Where-Object { $_ -match '^\s*(Dirs|Files|Bytes|Times)\s*:|ERROR|PAUSED|Access is denied' } | ForEach-Object { Write-Log ($_.ToString().Trim()) 'OUT' }
    # robocopy exit codes: 0-7 = success (bits for copied/extra/mismatch), 8+ = failure.
    if ($code -lt 8) { Write-Log ('{0}: done (code {1}).' -f $j.Label, $code) 'OK' }
    else { $failed++; Write-Log ('{0}: FAILED (code {1}). Files in use are a common cause - close the app and retry.' -f $j.Label, $code) 'ERROR' }
}
$Sync.Progress = $total
if ($failed) { Write-Log ('Copy finished with {0} item(s) failed.' -f $failed) 'DONE' }
else { Write-Log 'Copy finished successfully.' 'DONE' }
'@

$ToolboxDownloadScript = @'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls13
$items = @($Items)
$n = 0
foreach ($t in $items) {
    if ($Sync.Cancel) { Write-Log 'Stopped by user - remaining downloads skipped.' 'WARN'; break }
    $n++
    $Sync.Status = ('[{0}/{1}] {2}' -f $n, $items.Count, $t.Name)
    if ($t.Kind -eq 'page') {
        Write-Log ('{0}: no direct link - opening the vendor download page.' -f $t.Name)
        try { Start-Process $t.Url } catch { Write-Log ('Could not open page: {0}' -f $t.Url) 'WARN' }
        continue
    }
    $folder = Join-Path $Dir $t.Name
    try { New-Item -ItemType Directory -Path $folder -Force -ErrorAction SilentlyContinue | Out-Null } catch { }
    $file = Join-Path $folder $t.File
    Write-Log ('=== {0} ===' -f $t.Name) 'STEP'
    Write-Log ('> download {0}' -f $t.Url) 'CMD'
    try {
        Invoke-WebRequest -Uri $t.Url -OutFile $file -UseBasicParsing -TimeoutSec 180 -ErrorAction Stop
        $mb = [math]::Round((Get-Item -LiteralPath $file).Length / 1MB, 1)
        Write-Log ('{0}: downloaded {1} MB.' -f $t.Name, $mb) 'OK'
        if ($t.File -match '\.zip$') {
            try {
                Expand-Archive -LiteralPath $file -DestinationPath $folder -Force -ErrorAction Stop
                Write-Log ('{0}: extracted.' -f $t.Name) 'OK'
            } catch { Write-Log ('{0}: could not extract zip: {1}' -f $t.Name, $_.Exception.Message) 'WARN' }
        }
    } catch {
        Write-Log ('{0}: download failed ({1}). Use "Edit list" to fix the URL, or open the vendor page.' -f $t.Name, $_.Exception.Message) 'WARN'
    }
}
$Sync.Status = 'Toolbox: downloads finished'
Write-Log 'Toolbox downloads finished.' 'DONE'
'@

$TrackerUploadScript = @'
$ProgressPreference = 'SilentlyContinue'
$Sync.Status = 'Building diagnostic report...'

if ($BodyOverride) {
    # Caller supplied a ready-made record (e.g. a data-backup record); send it as-is.
    $body = [string]$BodyOverride
    if ($body.Length -gt 1000000) { $body = $body.Substring(0, 1000000) }
} else {
# ----- Build a plain-text report (NO passwords, product keys or recovery keys) -----
$sb = New-Object System.Text.StringBuilder
function AddL($t) { [void]$sb.AppendLine([string]$t) }
AddL 'BenchKit Diagnostic Report'
AddL ('Generated: {0}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm'))
if ($Tech) { AddL ('Technician: {0}' -f $Tech) }
AddL ('Ticket (work order): {0}' -f $Woid)
AddL ''
AddL '== System =='
# Explicit "Label: value" lines below are what the tracker's spec parser (prs_parse) reads
# to auto-fill the work order's make/model/serial/etc. Keep the label wording.
try {
    $cs = Get-CimInstance Win32_ComputerSystem
    $os = Get-CimInstance Win32_OperatingSystem
    $cpu = Get-CimInstance Win32_Processor | Select-Object -First 1
    $bios = Get-CimInstance Win32_BIOS
    $cv = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -ErrorAction SilentlyContinue
    $gpu = (@(Get-CimInstance Win32_VideoController | ForEach-Object { $_.Name }) -join '; ')
    AddL ('Computer Name: {0}' -f $env:COMPUTERNAME)
    AddL ('System Manufacturer: {0}' -f $cs.Manufacturer)
    AddL ('System Model: {0}' -f $cs.Model)
    AddL ('Serial Number: {0}' -f $bios.SerialNumber)
    AddL ('Operating System: {0} {1} (build {2}.{3})' -f ($os.Caption -replace 'Microsoft ', ''), $cv.DisplayVersion, $os.BuildNumber, $cv.UBR)
    AddL ('CPU: {0}' -f ($cpu.Name.Trim()))
    AddL ('RAM: {0:N1} GB' -f ($cs.TotalPhysicalMemory / 1GB))
    AddL ('Video Card: {0}' -f $gpu)
    AddL ('BIOS Version: {0}' -f $bios.SMBIOSBIOSVersion)
    $d = New-Object System.IO.DriveInfo($env:SystemDrive)
    AddL ('System Drive: {0:N0} GB total, {1:N1} GB free' -f ($d.TotalSize / 1GB), ($d.AvailableFreeSpace / 1GB))
} catch { AddL '(could not read full system details)' }
AddL ''
if ($IncludeFindings) {
    $fs = @($Findings | Where-Object { $_ -and $_.Severity -ne 'OK' })
    AddL ('== Diagnostics findings ({0}) ==' -f $fs.Count)
    if ($fs.Count) { foreach ($f in $fs) { AddL ('[{0}] {1}: {2}' -f $f.Severity, $f.Area, $f.Finding) } }
    else { AddL '(run Diagnostics > Scan for findings, or none were flagged)' }
    AddL ''
}
if ($IncludeWork) {
    $wk = @($Work)
    AddL ('== Work performed ({0}) ==' -f $wk.Count)
    if ($wk.Count) { foreach ($w in $wk) { AddL ('{0}  {1} - {2}' -f $w.Time, $w.Task, $w.Result) } }
    else { AddL '(no tasks run this session)' }
    AddL ''
}
if ($IncludeScan) {
    $rs = @($RemoteScan)
    AddL ('== Remote-access / security scan ({0}) ==' -f $rs.Count)
    if ($rs.Count) { foreach ($r in $rs) { AddL ('[{0}] {1} - {2}' -f $r.Severity, $r.Name, $r.Detail) } }
    else { AddL '(run the Security Scan tab; nothing recorded yet)' }
    AddL ''
}
AddL '(No passwords, product keys, Wi-Fi keys or BitLocker keys are included in this report.)'
$body = $sb.ToString()
if ($body.Length -gt 1000000) { $body = $body.Substring(0, 1000000) }
}

if ($PreviewOnly) {
    $pp = Join-Path $env:TEMP ('BenchKit_tracker_preview_{0:yyyyMMdd-HHmmss}.txt' -f (Get-Date))
    Set-Content -LiteralPath $pp -Value $body -Encoding UTF8
    Write-Log ('Report preview built ({0} characters). Opening it - nothing was uploaded.' -f $body.Length) 'OK'
    try { Start-Process notepad.exe $pp } catch { }
    $Sync.Status = 'Preview ready'
    return
}

# ----- Submit through the upload-code pipeline: GET for cookie + CSRF + nonce, then POST -----
$Sync.Status = ('Uploading to ticket #{0}...' -f $Woid)
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$sess = $null
try {
    Write-Log ('> GET {0}' -f $Url) 'CMD'
    $get = Invoke-WebRequest -Uri $Url -SessionVariable sess -UseBasicParsing -TimeoutSec 60 -ErrorAction Stop
} catch {
    Write-Log ('Could not reach the tracker: {0}' -f $_.Exception.Message) 'ERROR'; $Sync.Status = 'Upload failed'; return
}
$html = [string]$get.Content
$csrf = [regex]::Match($html, 'name="csrf"[^>]*value="([^"]+)"').Groups[1].Value
$nonce = [regex]::Match($html, 'name="nonce"[^>]*value="([^"]+)"').Groups[1].Value
if (-not $csrf -or -not $nonce) {
    Write-Log 'Could not read the upload form (check the Tracker URL points to report-upload.php).' 'ERROR'; $Sync.Status = 'Upload failed'; return
}
$form = @{ csrf = $csrf; nonce = $nonce; woid = $Woid; code = $Code; title = $Title; body = $body }
$rc = ''
try {
    Write-Log ('> POST report to ticket #{0} ({1} bytes)' -f $Woid, $body.Length) 'CMD'
    $resp = Invoke-WebRequest -Uri $Url -Method Post -WebSession $sess -Body $form -UseBasicParsing -TimeoutSec 120 -ErrorAction Stop
    $rc = [string]$resp.Content
} catch {
    try { $rc = (New-Object IO.StreamReader($_.Exception.Response.GetResponseStream())).ReadToEnd() } catch { }
    if (-not $rc) { Write-Log ('Upload failed: {0}' -f $_.Exception.Message) 'ERROR'; $Sync.Status = 'Upload failed'; return }
}
if ($rc -match 'Report submitted for technician review') {
    Write-Log ('Uploaded to ticket #{0}. Review and accept it in the ticket''s "Diagnostic Reports - Review / Upload Code" panel.' -f $Woid) 'OK'
    $Sync.Status = 'Upload complete'
} else {
    $m = [regex]::Match($rc, 'role="alert">([^<]+)<')
    if ($m.Success) { Write-Log ('Tracker rejected the upload: {0}' -f $m.Groups[1].Value.Trim()) 'WARN' }
    else { Write-Log 'Upload finished but the tracker did not confirm success - check the ticket.' 'WARN' }
    $Sync.Status = 'Upload finished with warnings'
}
'@

# Upload several saved report FILES to the ticket as TEXT (via the upload-code pipeline).
$TrackerUploadFilesScript = @'
$ProgressPreference = 'SilentlyContinue'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$files = @($Files); $ok = 0; $failc = 0; $n = 0
$sess = $null
try { $null = Invoke-WebRequest $Url -SessionVariable sess -UseBasicParsing -TimeoutSec 60 -ErrorAction Stop }
catch { Write-Log ('Could not reach the tracker: {0}' -f $_.Exception.Message) 'ERROR'; $Sync.Status = 'Upload failed'; return }
foreach ($f in $files) {
    if ($Sync.Cancel) { break }
    $n++; $Sync.Status = ('[{0}/{1}] uploading {2}' -f $n, $files.Count, [IO.Path]::GetFileName($f))
    if (-not (Test-Path -LiteralPath $f)) { Write-Log ('Missing: {0}' -f $f) 'WARN'; $failc++; continue }
    $raw = Get-Content -Raw -LiteralPath $f -ErrorAction SilentlyContinue
    if ($f -match '\.html?$') {
        $txt = $raw -replace '(?s)<(script|style)[^>]*>.*?</\1>', ' '
        $txt = $txt -replace '(?s)<[^>]+>', ' '
        $txt = [System.Net.WebUtility]::HtmlDecode($txt)
        $txt = ($txt -split "`r?`n" | ForEach-Object { ($_ -replace '[ \t]+', ' ').Trim() } | Where-Object { $_ -ne '' }) -join "`r`n"
    } else { $txt = $raw }
    if (-not $txt) { $txt = '(empty report)' }
    if ($txt.Length -gt 1000000) { $txt = $txt.Substring(0, 1000000) }
    try { $g = Invoke-WebRequest $Url -WebSession $sess -UseBasicParsing -TimeoutSec 60 -ErrorAction Stop } catch { Write-Log ('GET failed: {0}' -f $_.Exception.Message) 'WARN'; $failc++; continue }
    $html = [string]$g.Content
    $csrf = [regex]::Match($html, 'name="csrf"[^>]*value="([^"]+)"').Groups[1].Value
    $nonce = [regex]::Match($html, 'name="nonce"[^>]*value="([^"]+)"').Groups[1].Value
    if (-not $csrf -or -not $nonce) { Write-Log 'Could not read the upload token.' 'WARN'; $failc++; continue }
    $title = [IO.Path]::GetFileNameWithoutExtension($f); if ($title.Length -gt 160) { $title = $title.Substring(0, 160) }
    $form = @{ csrf = $csrf; nonce = $nonce; woid = $Woid; code = $Code; title = $title; body = $txt }
    $rc = ''
    try { $resp = Invoke-WebRequest $Url -Method Post -WebSession $sess -Body $form -UseBasicParsing -TimeoutSec 120 -ErrorAction Stop; $rc = [string]$resp.Content }
    catch { try { $rc = (New-Object IO.StreamReader($_.Exception.Response.GetResponseStream())).ReadToEnd() } catch { } }
    if ($rc -match 'Report submitted for technician review') { $ok++; Write-Log ('Uploaded as text: {0}' -f $title) 'OK' }
    else { $failc++; $m = [regex]::Match($rc, 'role="alert">([^<]+)<'); if ($m.Success) { Write-Log ('Rejected {0}: {1}' -f $title, $m.Groups[1].Value.Trim()) 'WARN' } else { Write-Log ('No confirmation for {0}' -f $title) 'WARN' } }
}
Write-Log ('Text upload done: {0} uploaded, {1} failed. Review/accept them in the ticket.' -f $ok, $failc) 'DONE'
$Sync.Status = 'Text upload complete'
'@

# Attach several HTML report FILES to the ticket as real PCRT attachments (via benchkit_attach.php).
$AttachFilesScript = @'
$ProgressPreference = 'SilentlyContinue'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$files = @($Files); $ok = 0; $failc = 0; $n = 0
foreach ($f in $files) {
    if ($Sync.Cancel) { break }
    $n++; $fn = [IO.Path]::GetFileName($f); $Sync.Status = ('[{0}/{1}] attaching {2}' -f $n, $files.Count, $fn)
    if (-not (Test-Path -LiteralPath $f)) { Write-Log ('Missing: {0}' -f $f) 'WARN'; $failc++; continue }
    $fileText = [IO.File]::ReadAllText($f, [Text.Encoding]::UTF8)
    $title = [IO.Path]::GetFileNameWithoutExtension($f); if ($title.Length -gt 160) { $title = $title.Substring(0, 160) }
    $boundary = '----BenchKit' + [Guid]::NewGuid().ToString('N')
    $LF = "`r`n"
    $sb = New-Object System.Text.StringBuilder
    foreach ($kv in @(@('hash', $Hash), @('woid', $Woid), @('title', $title))) {
        [void]$sb.Append('--' + $boundary + $LF)
        [void]$sb.Append('Content-Disposition: form-data; name="' + $kv[0] + '"' + $LF + $LF)
        [void]$sb.Append([string]$kv[1] + $LF)
    }
    [void]$sb.Append('--' + $boundary + $LF)
    [void]$sb.Append('Content-Disposition: form-data; name="report"; filename="' + $fn + '"' + $LF)
    [void]$sb.Append('Content-Type: text/html' + $LF + $LF)
    [void]$sb.Append($fileText + $LF)
    [void]$sb.Append('--' + $boundary + '--' + $LF)
    $bytes = [Text.Encoding]::UTF8.GetBytes($sb.ToString())
    $rc = ''
    try { $resp = Invoke-WebRequest $Url -Method Post -ContentType ('multipart/form-data; boundary={0}' -f $boundary) -Body $bytes -UseBasicParsing -TimeoutSec 120 -ErrorAction Stop; $rc = [string]$resp.Content }
    catch { try { $rc = (New-Object IO.StreamReader($_.Exception.Response.GetResponseStream())).ReadToEnd() } catch { }; if (-not $rc) { $rc = 'ERROR: ' + $_.Exception.Message } }
    if ($rc -match '^OK:') { $ok++; Write-Log ('Attached HTML: {0}' -f $title) 'OK' }
    else { $failc++; Write-Log ('Attach failed for {0}: {1}' -f $title, $rc) 'WARN' }
}
Write-Log ('HTML attach done: {0} attached, {1} failed.' -f $ok, $failc) 'DONE'
$Sync.Status = 'HTML attach complete'
'@
#endregion

#region ---- UI helpers -----------------------------------------------------------------------
$Font = New-Object System.Drawing.Font('Segoe UI', 9)
$Mono = New-Object System.Drawing.Font('Consolas', 9)

function New-Ctl {
    param([string]$Type, [hashtable]$P = @{})
    $c = New-Object ("System.Windows.Forms.$Type")
    foreach ($k in $P.Keys) { $c.$k = $P[$k] }
    return $c
}
function New-Pad {
    # Accepts New-Pad 8  OR  New-Pad 8, 2, 8, 2  (PowerShell turns the comma form into one array)
    # OR New-Pad 8 2 8 2. All three are normalized here so callers don't have to care.
    param($a, $b = -1, $c = -1, $d = -1)
    if ($a -is [System.Array]) {
        $v = @($a)
        $a = [int]$v[0]
        $b = if ($v.Count -gt 1) { [int]$v[1] } else { -1 }
        $c = if ($v.Count -gt 2) { [int]$v[2] } else { -1 }
        $d = if ($v.Count -gt 3) { [int]$v[3] } else { -1 }
    } else {
        $a = [int]$a; $b = [int]$b; $c = [int]$c; $d = [int]$d
    }
    if ($b -lt 0) { return New-Object System.Windows.Forms.Padding($a) }
    return New-Object System.Windows.Forms.Padding($a, $b, $c, $d)
}
function Get-AppTitle {
    $n = if ($script:Settings.CompanyName) { $script:Settings.CompanyName } else { 'Cybrac.com' }
    return ('{0} - Tech Toolkit' -f $n)
}
function Get-LogoImage {
    $p = $script:Settings.LogoPath
    if (-not $p -or -not (Test-Path -LiteralPath $p)) { return $null }
    try { $bytes = [IO.File]::ReadAllBytes($p); $ms = New-Object IO.MemoryStream(, $bytes); return [System.Drawing.Image]::FromStream($ms) } catch { return $null }
}
function Get-LogoDataUri {
    $p = $script:Settings.LogoPath
    if (-not $p -or -not (Test-Path -LiteralPath $p)) { return '' }
    try {
        $ext = ([IO.Path]::GetExtension($p)).TrimStart('.').ToLower()
        $mime = switch ($ext) { 'png' { 'image/png' } 'jpg' { 'image/jpeg' } 'jpeg' { 'image/jpeg' } 'gif' { 'image/gif' } 'bmp' { 'image/bmp' } 'svg' { 'image/svg+xml' } default { 'image/png' } }
        return ('data:{0};base64,{1}' -f $mime, [Convert]::ToBase64String([IO.File]::ReadAllBytes($p)))
    } catch { return '' }
}
function Set-Brand {
    if ($script:form) { $script:form.Text = Get-AppTitle }
    if ($script:lblBrand) { $script:lblBrand.Text = Get-AppTitle }
    if ($script:lblBrandR) {
        $bits = @()
        if ($script:Settings.TechName)       { $bits += 'Tech: ' + $script:Settings.TechName }
        if ($script:Settings.CompanyWebsite) { $bits += $script:Settings.CompanyWebsite }
        if ($script:Settings.CompanyPhone)   { $bits += $script:Settings.CompanyPhone }
        $line = ($bits -join '     ')
        $script:lblBrandR.Text = if ($line) { ('{0}     v{1}' -f $line, $AppVersion) } else { ('v{0}' -f $AppVersion) }
    }
    if ($script:picLogo) {
        $img = Get-LogoImage
        try { if ($script:picLogo.Image) { $script:picLogo.Image.Dispose() } } catch { }
        if ($img) {
            $script:picLogo.Image = $img
            $w = [int][math]::Round($img.Width * (36.0 / [math]::Max(1, $img.Height)))
            $script:picLogo.Width = [math]::Min(240, [math]::Max(48, $w))
            $script:picLogo.Visible = $true
        } else { $script:picLogo.Image = $null; $script:picLogo.Width = 0; $script:picLogo.Visible = $false }
    }
    Set-AppIcon
}
function Set-AppIcon {
    # Use the shop logo as the window / taskbar icon. Accepts a .ico directly, or converts a PNG/JPG.
    if (-not $script:form) { return }
    $p = $script:Settings.LogoPath
    if (-not $p -or -not (Test-Path -LiteralPath $p)) { return }
    try {
        if ($p -match '\.ico$') {
            $script:form.Icon = New-Object System.Drawing.Icon($p)
        } else {
            $img = Get-LogoImage
            if ($img) {
                $bmp = New-Object System.Drawing.Bitmap($img, (New-Object System.Drawing.Size(32, 32)))
                $script:form.Icon = [System.Drawing.Icon]::FromHandle($bmp.GetHicon())
            }
        }
    } catch { }
}
function Show-Msg([string]$Text, [string]$Icon = 'Information') {
    [void][System.Windows.Forms.MessageBox]::Show($form, $Text, (Get-AppTitle),
        [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]$Icon)
}
function Confirm-YesNo([string]$Text) {
    $r = [System.Windows.Forms.MessageBox]::Show($form, $Text, (Get-AppTitle),
        [System.Windows.Forms.MessageBoxButtons]::YesNo, [System.Windows.Forms.MessageBoxIcon]::Question)
    return ($r -eq [System.Windows.Forms.DialogResult]::Yes)
}

function Set-ControlTheme($c) {
    if ($c -eq $script:txtOut) { return }
    $n = $c.GetType().Name
    if ($n -in 'TextBox', 'ListView', 'CheckedListBox', 'ListBox', 'ComboBox') {
        $c.BackColor = $script:Th.Input; $c.ForeColor = $script:Th.Fg
    } elseif ($n -eq 'Button') {
        if ($script:PrimaryBtns -and $script:PrimaryBtns.Contains($c)) {
            $c.FlatStyle = 'Flat'; $c.FlatAppearance.BorderSize = 0
            $c.BackColor = $script:Th.Accent; $c.ForeColor = $script:Th.AccentFg
            $c.FlatAppearance.MouseOverBackColor = $script:Th.AccentHover
        } else {
            $c.FlatStyle = 'Flat'; $c.BackColor = $script:Th.Btn; $c.ForeColor = $script:Th.Fg
            $c.FlatAppearance.BorderColor = $script:Th.Border
            $c.FlatAppearance.MouseOverBackColor = $script:Th.BtnHover
        }
    } elseif ($n -ne 'ProgressBar') {
        $c.BackColor = $script:Th.Bg; $c.ForeColor = $script:Th.Fg
    }
    foreach ($ch in $c.Controls) { Set-ControlTheme $ch }
}

function RGB($r, $g, $b) { return [System.Drawing.Color]::FromArgb($r, $g, $b) }
function Apply-Chrome {
    if ($script:header) {
        $script:header.BackColor = $script:Th.HeaderBg
        foreach ($lb in @($script:lblBrand, $script:lblBrandR)) { if ($lb) { $lb.BackColor = $script:Th.HeaderBg; $lb.ForeColor = $script:Th.HeaderFg } }
        if ($script:picLogo) { $script:picLogo.BackColor = $script:Th.HeaderBg }
    }
    if ($script:tabs) { $script:tabs.BackColor = $script:Th.Nav; $script:tabs.Invalidate() }
}
function Set-Theme([string]$Name) {
    $script:IsDark = ($Name -eq 'Dark')
    if ($script:IsDark) {
        $script:Th = @{
            Bg = (RGB 32 32 34); Input = (RGB 45 45 48); Fg = (RGB 232 232 232)
            Btn = (RGB 60 60 66); BtnHover = (RGB 74 74 82); Border = (RGB 90 90 96)
            Accent = (RGB 76 141 255); AccentHover = (RGB 104 161 255); AccentFg = (RGB 255 255 255)
            HeaderBg = (RGB 24 26 40); HeaderFg = (RGB 236 238 245)
            Nav = (RGB 38 38 42); NavSel = (RGB 52 56 70); NavSelFg = (RGB 255 255 255)
        }
    } else {
        $script:Th = @{
            Bg = (RGB 245 246 248); Input = (RGB 255 255 255); Fg = (RGB 31 35 40)
            Btn = (RGB 255 255 255); BtnHover = (RGB 236 240 246); Border = (RGB 198 204 212)
            Accent = (RGB 45 108 223); AccentHover = (RGB 32 92 200); AccentFg = (RGB 255 255 255)
            HeaderBg = (RGB 31 58 95); HeaderFg = (RGB 255 255 255)
            Nav = (RGB 238 241 246); NavSel = (RGB 255 255 255); NavSelFg = (RGB 31 58 95)
        }
    }
    if ($script:form) { Set-ControlTheme $script:form; Apply-Chrome }
}

function Show-Confirm([string]$Title, [string]$Text, [string]$OkText = 'Run') {
    $f = New-Ctl Form @{ Text = $Title; Size = [System.Drawing.Size]::new(760, 500); StartPosition = 'CenterParent'; Font = $Font; MinimizeBox = $false; MaximizeBox = $false; ShowInTaskbar = $false }
    $tb = New-Ctl TextBox @{ Multiline = $true; ReadOnly = $true; ScrollBars = 'Vertical'; Dock = 'Fill'; Font = $Mono; Text = $Text; TabStop = $false }
    $pnl = New-Ctl FlowLayoutPanel @{ Dock = 'Bottom'; Height = 46; FlowDirection = 'RightToLeft'; Padding = (New-Pad 6) }
    $cancel = New-Ctl Button @{ Text = 'Cancel'; Width = 110; Height = 30; DialogResult = 'Cancel' }
    $ok     = New-Ctl Button @{ Text = $OkText; Width = 110; Height = 30; DialogResult = 'OK' }
    $pnl.Controls.AddRange([System.Windows.Forms.Control[]]@($cancel, $ok))
    $f.Controls.Add($tb); $f.Controls.Add($pnl); $tb.BringToFront()
    $f.AcceptButton = $ok; $f.CancelButton = $cancel
    Set-ControlTheme $f
    $r = $f.ShowDialog($script:form)
    $f.Dispose()
    return ($r -eq [System.Windows.Forms.DialogResult]::OK)
}

function Write-UiLines([string[]]$Lines) {
    if (-not $Lines) { return }
    $toLog = New-Object System.Collections.Generic.List[string]
    foreach ($l in $Lines) {
        if ($l.StartsWith('@@BKPROGRESS@@')) {
            # Live progress: keep rewriting one line in place instead of adding a new line each tick.
            $txt = $l.Substring(14)
            $blue = [System.Drawing.Color]::FromArgb(120, 200, 255)
            if (-not $script:ProgActive) {
                if ($script:txtOut.TextLength -gt 0) { $script:txtOut.AppendText("`n") }
                $script:ProgStart = $script:txtOut.TextLength
                $script:txtOut.SelectionStart = $script:ProgStart; $script:txtOut.SelectionLength = 0
                $script:txtOut.SelectionColor = $blue
                $script:txtOut.AppendText($txt)
                $script:ProgActive = $true
            } else {
                $script:txtOut.Select($script:ProgStart, $script:txtOut.TextLength - $script:ProgStart)
                $script:txtOut.SelectionColor = $blue
                $script:txtOut.SelectedText = $txt
            }
            $script:txtOut.SelectionStart = $script:txtOut.TextLength
            $script:txtOut.ScrollToCaret()
            continue
        }
        if ($script:ProgActive) { $script:txtOut.AppendText("`n"); $script:ProgActive = $false }
        $color = [System.Drawing.Color]::FromArgb(210, 210, 210)
        if     ($l -match '\[ERROR\]') { $color = [System.Drawing.Color]::FromArgb(255, 110, 110) }
        elseif ($l -match '\[WARN\]')  { $color = [System.Drawing.Color]::FromArgb(255, 190, 90) }
        elseif ($l -match '\[OK\]')    { $color = [System.Drawing.Color]::FromArgb(110, 220, 140) }
        elseif ($l -match '\[(STEP|DONE)\]') { $color = [System.Drawing.Color]::FromArgb(110, 190, 255) }
        elseif ($l -match '\[(CMD|OUT)\]')   { $color = [System.Drawing.Color]::FromArgb(150, 150, 150) }
        $script:txtOut.SelectionStart  = $script:txtOut.TextLength
        $script:txtOut.SelectionLength = 0
        $script:txtOut.SelectionColor  = $color
        $script:txtOut.AppendText($l + "`n")
        $toLog.Add($l)
    }
    $script:txtOut.ScrollToCaret()
    if ($toLog.Count) { try { Add-Content -LiteralPath $script:LogFile -Value $toLog.ToArray() -Encoding UTF8 } catch { } }
}
function Write-Ui([string]$Message, [string]$Level = 'INFO') {
    Write-UiLines @(('{0} [{1}] {2}' -f (Get-Date -Format 'HH:mm:ss'), $Level, $Message))
}

function Start-Background {
    param([string]$Script, [hashtable]$Vars = @{}, [string]$Status = 'Working...', [int]$Total = 0, [scriptblock]$OnComplete)
    if ($Sync.Busy) { Show-Msg 'Another task is still running. Wait for it to finish, or press Stop.'; return }
    $Sync.Busy = $true; $Sync.Cancel = $false; $Sync.Status = $Status; $Sync.Progress = 0; $Sync.Total = $Total
    $script:OnComplete = $OnComplete
    $rs = [runspacefactory]::CreateRunspace()
    $rs.ApartmentState = 'STA'
    $rs.Open()
    $rs.SessionStateProxy.SetVariable('Sync', $Sync)
    foreach ($k in $Vars.Keys) { $rs.SessionStateProxy.SetVariable($k, $Vars[$k]) }
    $ps = [powershell]::Create()
    $ps.Runspace = $rs
    [void]$ps.AddScript($Common + "`r`n" + $Script)
    $script:BgPS     = $ps
    $script:BgHandle = $ps.BeginInvoke()
    $script:btnStop.Enabled = $true
    if ($Total -gt 0) { $script:prog.Style = 'Continuous'; $script:prog.Maximum = $Total; $script:prog.Value = 0 }
    else { $script:prog.Style = 'Marquee' }
}

function Invoke-Actions {
    param([string[]]$Ids, [string]$Label = 'Running tasks')
    $ids = @($script:ActionOrder | Where-Object { $Ids -contains $_ })
    if (-not $ids.Count) { Show-Msg 'Tick at least one task first.'; return }
    if ($Sync.Busy) { Show-Msg 'Another task is still running. Wait for it to finish, or press Stop.'; return }

    $needsAsk = [bool]$script:Settings.ConfirmCommands
    $lines = New-Object System.Collections.Generic.List[string]
    $lines.Add(('These {0} task(s) will run in this order:' -f $ids.Count)); $lines.Add('')
    $i = 0
    foreach ($id in $ids) {
        $a = $script:Actions[$id]; $i++
        $lines.Add(('{0}. {1}' -f $i, $a.Name))
        if ($a.Desc) { $lines.Add(('     What it does: {0}' -f $a.Desc)) }
        $lines.Add(('     Runs: {0}' -f $a.Preview))
        if ($a.Warning) { $lines.Add(('     NOTE: {0}' -f $a.Warning)); $needsAsk = $true }
        if ($a.Reboot)  { $lines.Add('     A restart is needed to finish this one.'); $needsAsk = $true }
        $lines.Add('')
    }
    if ($needsAsk -and -not (Show-Confirm -Title 'Review before running' -Text ($lines -join "`r`n"))) { return }

    # Let the tech name the restore point so it's easy to find later in System Restore.
    $Sync.RestoreLabel = ''
    if ($ids -contains 'restorepoint') {
        $nm = [Microsoft.VisualBasic.Interaction]::InputBox("Name this restore point (what you're about to do), or leave blank for a default:", 'Restore point name', 'Before BenchKit work')
        $Sync.RestoreLabel = ($nm -replace '[\r\n]+', ' ').Trim()
    }

    # Let the tech label the speed test (Before / After) so the report can compare runs.
    $Sync.SpeedLabel = ''
    if ($ids -contains 'speedtest') {
        $sl = [Microsoft.VisualBasic.Interaction]::InputBox('Label for this speed test (e.g. Before or After), or leave blank:', 'Speed test label', 'Before')
        $Sync.SpeedLabel = ($sl -replace '[\r\n]+', ' ').Trim()
    }

    $items = @(foreach ($id in $ids) {
        $a = $script:Actions[$id]
        [pscustomobject]@{ Id = $id; Name = $a.Name; Script = $a.Script; Reboot = $a.Reboot }
    })
    Start-Background -Script $script:RunnerScript -Vars @{ Items = $items } -Status $Label -Total $items.Count -OnComplete {
        if ($Sync.RebootNeeded) {
            $Sync.RebootNeeded = $false
            if (Confirm-YesNo 'Some fixes need a restart to finish. Restart in 15 seconds?') {
                Start-Process shutdown.exe -ArgumentList '/r /t 15 /c "Restarting to finish repairs"' -WindowStyle Hidden
            }
        }
    }
}

function Get-PCSummary {
    try {
        $cs  = Get-CimInstance Win32_ComputerSystem
        $os  = Get-CimInstance Win32_OperatingSystem
        $cpu = Get-CimInstance Win32_Processor | Select-Object -First 1
        $bio = Get-CimInstance Win32_BIOS
        $cv  = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -ErrorAction SilentlyContinue
        $gpu = (@(Get-CimInstance Win32_VideoController | ForEach-Object { $_.Name }) -join "`r`n            ")
        $sysDrive = New-Object System.IO.DriveInfo($env:SystemDrive)
        return (@(
            ('Computer:   {0}' -f $env:COMPUTERNAME)
            ('Model:      {0} {1}' -f $cs.Manufacturer, $cs.Model)
            ('Serial:     {0}' -f $bio.SerialNumber)
            ('Windows:    {0} {1}' -f ($os.Caption -replace 'Microsoft ', ''), $cv.DisplayVersion)
            ('Build:      {0}.{1}' -f $os.BuildNumber, $cv.UBR)
            ('CPU:        {0}' -f $cpu.Name.Trim())
            ('Memory:     {0:N1} GB' -f ($cs.TotalPhysicalMemory / 1GB))
            ('Graphics:   {0}' -f $gpu)
            ('System drive: {0:N0} GB ({1:N0} GB free)' -f ($sysDrive.TotalSize / 1GB), ($sysDrive.AvailableFreeSpace / 1GB))
            ('Installed:  {0:yyyy-MM-dd}' -f $os.InstallDate)
        ) -join "`r`n")
    } catch { return 'Could not read system details.' }
}
#endregion

$script:PrimaryBtns = New-Object System.Collections.ArrayList
Set-Theme $Settings.Theme

#region ---- Main window --------------------------------------------------------------------
$form = New-Ctl Form @{
    Text = (Get-AppTitle); Size = [System.Drawing.Size]::new(1220, 820); MinimumSize = [System.Drawing.Size]::new(980, 640)
    StartPosition = 'CenterScreen'; Font = $Font
}

# Header bar
$header = New-Ctl Panel @{ Dock = 'Top'; Height = 52 }
$lblBrand = New-Ctl Label @{ Dock = 'Left'; Width = 520; TextAlign = 'MiddleLeft'; Padding = (New-Pad 18, 0, 0, 0)
    Font = (New-Object System.Drawing.Font('Segoe UI Semibold', 14, [System.Drawing.FontStyle]::Bold)) }
$lblBrandR = New-Ctl Label @{ Dock = 'Right'; Width = 340; TextAlign = 'MiddleRight'; Padding = (New-Pad 0, 0, 18, 0)
    Font = (New-Object System.Drawing.Font('Segoe UI', 9)); Text = ('v{0}' -f $AppVersion) }
$picLogo = New-Ctl PictureBox @{ Dock = 'Left'; Width = 0; SizeMode = 'Zoom'; Margin = (New-Pad 0); Padding = (New-Pad 8, 6, 4, 6) }
$header.Controls.Add($lblBrandR); $header.Controls.Add($lblBrand); $header.Controls.Add($picLogo)

# Current-job bar (Technician / Customer / Ticket) - shared by every report, note and scan.
$jobBar = New-Ctl Panel @{ Dock = 'Top'; Height = 34 }
$jobFlow = New-Ctl FlowLayoutPanel @{ Dock = 'Fill'; WrapContents = $false; AutoSize = $false; Padding = (New-Pad 14, 4, 0, 0) }
$lblJobT = New-Ctl Label @{ Text = 'Technician:'; AutoSize = $true; Padding = (New-Pad 0, 6, 4, 0) }
$txtTech = New-Ctl TextBox @{ Width = 150; Text = $Settings.TechName }
$lblJobC = New-Ctl Label @{ Text = 'Customer:'; AutoSize = $true; Padding = (New-Pad 16, 6, 4, 0) }
$txtCustomer = New-Ctl TextBox @{ Width = 240 }
$lblJobK = New-Ctl Label @{ Text = 'Ticket #:'; AutoSize = $true; Padding = (New-Pad 16, 6, 4, 0) }
$txtTicket = New-Ctl TextBox @{ Width = 120 }
$jobFlow.Controls.AddRange([System.Windows.Forms.Control[]]@($lblJobT, $txtTech, $lblJobC, $txtCustomer, $lblJobK, $txtTicket))
$jobBar.Controls.Add($jobFlow)

$split = New-Ctl SplitContainer @{ Dock = 'Fill'; Orientation = 'Horizontal'; SplitterWidth = 6 }
$tabs  = New-Ctl TabControl @{ Dock = 'Fill'; Alignment = 'Left'; SizeMode = 'Fixed'; DrawMode = 'OwnerDrawFixed'
    Multiline = $true; ItemSize = [System.Drawing.Size]::new(30, 148); Padding = [System.Drawing.Point]::new(0, 0) }
$tabs.Add_DrawItem({
    param($s, $e)
    try {
        $idx = $e.Index
        $rect = $s.GetTabRect($idx)
        $sel = ($idx -eq $s.SelectedIndex)
        $bg = if ($sel) { $script:Th.NavSel } else { $script:Th.Nav }
        $fg = if ($sel) { $script:Th.NavSelFg } else { $script:Th.Fg }
        $e.Graphics.FillRectangle((New-Object System.Drawing.SolidBrush $bg), $rect)
        if ($sel) {
            $bar = New-Object System.Drawing.Rectangle($rect.Left, $rect.Top, 4, $rect.Height)
            $e.Graphics.FillRectangle((New-Object System.Drawing.SolidBrush $script:Th.Accent), $bar)
        }
        $sf = New-Object System.Drawing.StringFormat
        $sf.LineAlignment = 'Center'; $sf.Alignment = 'Near'
        $tr = New-Object System.Drawing.RectangleF(($rect.Left + 16), $rect.Top, ($rect.Width - 18), $rect.Height)
        $e.Graphics.DrawString($s.TabPages[$idx].Text, $s.Font, (New-Object System.Drawing.SolidBrush $fg), $tr, $sf)
    } catch { }
})
$split.Panel1.Controls.Add($tabs)

# Output console + status bar
$txtOut = New-Ctl RichTextBox @{ Dock = 'Fill'; ReadOnly = $true; Font = $Mono; BackColor = [System.Drawing.Color]::FromArgb(18, 18, 20); ForeColor = [System.Drawing.Color]::Gainsboro; BorderStyle = 'None'; WordWrap = $false; DetectUrls = $false }
$statusBar = New-Ctl Panel @{ Dock = 'Bottom'; Height = 38; Padding = (New-Pad 6, 6, 6, 4) }
$prog      = New-Ctl ProgressBar @{ Dock = 'Left'; Width = 260; MarqueeAnimationSpeed = 30 }
$lblStatus = New-Ctl Label @{ Dock = 'Fill'; Text = 'Ready'; TextAlign = 'MiddleLeft'; Padding = (New-Pad 10, 0, 0, 0) }
$statusBtns = New-Ctl FlowLayoutPanel @{ Dock = 'Right'; Width = 340; FlowDirection = 'RightToLeft'; WrapContents = $false }
$btnStop   = New-Ctl Button @{ Text = 'Stop'; Width = 80; Height = 26; Enabled = $false }
$btnClear  = New-Ctl Button @{ Text = 'Clear output'; Width = 100; Height = 26 }
$btnLogs   = New-Ctl Button @{ Text = 'Open logs'; Width = 90; Height = 26 }
$statusBtns.Controls.AddRange([System.Windows.Forms.Control[]]@($btnStop, $btnClear, $btnLogs))
$statusBar.Controls.Add($lblStatus); $statusBar.Controls.Add($statusBtns); $statusBar.Controls.Add($prog); $lblStatus.BringToFront()
$split.Panel2.Controls.Add($txtOut); $split.Panel2.Controls.Add($statusBar); $txtOut.BringToFront()

$btnStop.Add_Click({ $Sync.Cancel = $true; $lblStatus.Text = 'Stopping after the current step...'; $btnStop.Enabled = $false })
$btnClear.Add_Click({ $txtOut.Clear(); $script:ProgActive = $false })
$btnLogs.Add_Click({ Start-Process explorer.exe $LogDir })

# ---- Dashboard ----------------------------------------------------------------------------
$tabDash = New-Ctl TabPage @{ Text = 'Dashboard'; Padding = (New-Pad 8) }
$gbMon = New-Ctl GroupBox @{ Text = 'Live monitor'; Dock = 'Top'; Height = 160; Padding = (New-Pad 10, 6, 10, 6) }
$tlMon = New-Ctl TableLayoutPanel @{ Dock = 'Fill'; ColumnCount = 3; RowCount = 4 }
[void]$tlMon.ColumnStyles.Add((New-Object System.Windows.Forms.ColumnStyle([System.Windows.Forms.SizeType]::Absolute, 140)))
[void]$tlMon.ColumnStyles.Add((New-Object System.Windows.Forms.ColumnStyle([System.Windows.Forms.SizeType]::Percent, 100)))
[void]$tlMon.ColumnStyles.Add((New-Object System.Windows.Forms.ColumnStyle([System.Windows.Forms.SizeType]::Absolute, 230)))
for ($r = 0; $r -lt 4; $r++) { [void]$tlMon.RowStyles.Add((New-Object System.Windows.Forms.RowStyle([System.Windows.Forms.SizeType]::Percent, 25))) }
function New-Meter([int]$Row, [string]$Name) {
    $l = New-Ctl Label @{ Text = $Name; Dock = 'Fill'; TextAlign = 'MiddleLeft' }
    $b = New-Ctl ProgressBar @{ Dock = 'Fill'; Minimum = 0; Maximum = 100; Margin = (New-Pad 3, 7, 12, 7) }
    $v = New-Ctl Label @{ Text = '-'; Dock = 'Fill'; TextAlign = 'MiddleLeft' }
    $tlMon.Controls.Add($l, 0, $Row); $tlMon.Controls.Add($b, 1, $Row); $tlMon.Controls.Add($v, 2, $Row)
    return @{ Bar = $b; Value = $v }
}
$mCpu  = New-Meter 0 'Processor'
$mRam  = New-Meter 1 'Memory'
$mDisk = New-Meter 2 'System drive space'
$mIO   = New-Meter 3 'Disk activity'
$gbMon.Controls.Add($tlMon)

$gbPC = New-Ctl GroupBox @{ Text = 'This PC'; Dock = 'Left'; Width = 500; Padding = (New-Pad 10) }
$lblPC = New-Ctl Label @{ Dock = 'Fill'; Font = $Mono; Text = 'Loading...' }
$lblUptime = New-Ctl Label @{ Dock = 'Bottom'; Height = 22; Font = $Mono }
$gbPC.Controls.Add($lblPC); $gbPC.Controls.Add($lblUptime); $lblPC.BringToFront()

$gbProc = New-Ctl GroupBox @{ Text = 'Top processes by memory'; Dock = 'Fill'; Padding = (New-Pad 10) }
$lvProc = New-Ctl ListView @{ View = 'Details'; Dock = 'Fill'; FullRowSelect = $true; HeaderStyle = 'Nonclickable' }
[void]$lvProc.Columns.Add('Process', 200); [void]$lvProc.Columns.Add('PID', 70); [void]$lvProc.Columns.Add('Memory (MB)', 110); [void]$lvProc.Columns.Add('CPU time (s)', 100)
$gbProc.Controls.Add($lvProc)

$dashBtns = New-Ctl FlowLayoutPanel @{ Dock = 'Bottom'; Height = 44; Padding = (New-Pad 0, 8, 0, 0) }
$btnDashDiag   = New-Ctl Button @{ Text = 'Run Smart Diagnostics'; Width = 170; Height = 30 }
$btnDashTune   = New-Ctl Button @{ Text = 'Quick Tune-up'; Width = 120; Height = 30 }
$btnDashRemote = New-Ctl Button @{ Text = 'Scan remote-access'; Width = 150; Height = 30 }
$btnDashDeploy = New-Ctl Button @{ Text = 'Deploy remote support'; Width = 170; Height = 30 }
$btnDashReport = New-Ctl Button @{ Text = 'Customer report'; Width = 130; Height = 30 }
$dashBtns.Controls.AddRange([System.Windows.Forms.Control[]]@($btnDashDiag, $btnDashTune, $btnDashRemote, $btnDashDeploy, $btnDashReport))

# Quick power-plan chooser (full controls live on the Power tab).
$dashPowerBar = New-Ctl FlowLayoutPanel @{ Dock = 'Bottom'; Height = 34; WrapContents = $false; AutoSize = $false }
$lblDashPower = New-Ctl Label @{ Text = 'Power plan:'; AutoSize = $true; Padding = (New-Pad 0, 7, 6, 0) }
$cmbDashPower = New-Ctl ComboBox @{ Width = 300; DropDownStyle = 'DropDownList' }
$cmbDashPower.DisplayMember = 'Display'; $cmbDashPower.ValueMember = 'Tag'
$dashPowerBar.Controls.AddRange([System.Windows.Forms.Control[]]@($lblDashPower, $cmbDashPower))
$script:DashPowerLoading = $false
$cmbDashPower.Add_SelectedIndexChanged({
    if ($script:DashPowerLoading) { return }
    $sel = $cmbDashPower.SelectedItem; if (-not $sel) { return }
    $tag = [string]$sel.Tag
    if     ($tag -eq 'HIGH') { Enable-PowerPlan $PwHighGuid 'High performance' }
    elseif ($tag -eq 'ULT')  { Enable-PowerPlan $PwUltGuid 'Ultimate performance' }
    else { $null = Invoke-PowerCfg @('/setactive', $tag); Write-Ui ('Active power plan set to "{0}".' -f ($sel.Display -replace '\s*\(active\)\s*$', '')) 'OK' }
    if (Get-Command Update-PowerList -ErrorAction SilentlyContinue) { Update-PowerList }
    Update-DashPower
})

$tabDash.Controls.Add($gbProc); $tabDash.Controls.Add($gbPC); $tabDash.Controls.Add($gbMon)
$tabDash.Controls.Add($dashBtns); $tabDash.Controls.Add($dashPowerBar)
$gbProc.BringToFront()

try { $CpuCounter = New-Object System.Diagnostics.PerformanceCounter('Processor', '% Processor Time', '_Total'); [void]$CpuCounter.NextValue() } catch { $CpuCounter = $null }
try { $IdleCounter = New-Object System.Diagnostics.PerformanceCounter('PhysicalDisk', '% Idle Time', '_Total'); [void]$IdleCounter.NextValue() } catch { $IdleCounter = $null }

function Set-Meter($M, [double]$Pct, [string]$Text) {
    $M.Bar.Value  = [int][math]::Max(0, [math]::Min(100, $Pct))
    $M.Value.Text = $Text
}
function Update-Monitor {
    try {
        $cpu = 0
        if ($script:CpuCounter) { $cpu = $script:CpuCounter.NextValue() }
        else { $cpu = (Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Average).Average }
        Set-Meter $mCpu $cpu ('{0:N0}%' -f $cpu)

        $os = Get-CimInstance Win32_OperatingSystem -Property FreePhysicalMemory, TotalVisibleMemorySize, LastBootUpTime
        $totGB = $os.TotalVisibleMemorySize / 1MB
        $useGB = ($os.TotalVisibleMemorySize - $os.FreePhysicalMemory) / 1MB
        Set-Meter $mRam ($useGB / $totGB * 100) ('{0:N1} of {1:N1} GB ({2:N0}%)' -f $useGB, $totGB, ($useGB / $totGB * 100))

        $d = New-Object System.IO.DriveInfo($env:SystemDrive)
        $usedPct = ($d.TotalSize - $d.AvailableFreeSpace) / $d.TotalSize * 100
        Set-Meter $mDisk $usedPct ('{0:N0}% used, {1:N1} GB free' -f $usedPct, ($d.AvailableFreeSpace / 1GB))

        if ($script:IdleCounter) {
            $io = 100 - $script:IdleCounter.NextValue()
            Set-Meter $mIO $io ('{0:N0}% busy' -f [math]::Max(0, $io))
        }
        $up = (Get-Date) - $os.LastBootUpTime
        $lblUptime.Text = ('Up time:    {0}d {1}h {2}m' -f $up.Days, $up.Hours, $up.Minutes)

        $lvProc.BeginUpdate(); $lvProc.Items.Clear()
        Get-Process | Sort-Object WorkingSet64 -Descending | Select-Object -First 12 | ForEach-Object {
            $it = New-Object System.Windows.Forms.ListViewItem($_.ProcessName)
            [void]$it.SubItems.Add([string]$_.Id)
            [void]$it.SubItems.Add(('{0:N0}' -f ($_.WorkingSet64 / 1MB)))
            $cpuT = ''; try { $cpuT = '{0:N0}' -f $_.TotalProcessorTime.TotalSeconds } catch { }
            [void]$it.SubItems.Add($cpuT)
            [void]$lvProc.Items.Add($it)
        }
        $lvProc.EndUpdate()
    } catch { }
}

# ---- Diagnostics --------------------------------------------------------------------------
$tabDiag = New-Ctl TabPage @{ Text = 'Diagnostics'; Padding = (New-Pad 8) }
$diagTop = New-Ctl FlowLayoutPanel @{ Dock = 'Top'; Height = 44; WrapContents = $false }
$btnScan = New-Ctl Button @{ Text = 'Scan now'; Width = 120; Height = 30 }
$btnFix  = New-Ctl Button @{ Text = 'Fix checked issues'; Width = 160; Height = 30 }
$lblDiag = New-Ctl Label @{ Text = 'Checks storage, drive health, crashes, drivers, updates, security, services and network. Read-only - nothing changes until you press Fix.'; AutoSize = $true; Padding = (New-Pad 10, 8, 0, 0) }
$diagTop.Controls.AddRange([System.Windows.Forms.Control[]]@($btnScan, $btnFix, $lblDiag))
$lvDiag = New-Ctl ListView @{ View = 'Details'; Dock = 'Fill'; CheckBoxes = $true; FullRowSelect = $true }
[void]$lvDiag.Columns.Add('Severity', 85); [void]$lvDiag.Columns.Add('Area', 100); [void]$lvDiag.Columns.Add('Finding', 560); [void]$lvDiag.Columns.Add('Suggested fix', 360)
$tabDiag.Controls.Add($lvDiag); $tabDiag.Controls.Add($diagTop); $lvDiag.BringToFront()

function Show-Findings {
    $lvDiag.BeginUpdate(); $lvDiag.Items.Clear()
    $rank = @{ Critical = 0; Warning = 1; Info = 2; OK = 3 }
    foreach ($x in (@($Sync.Findings) | Where-Object { $_ } | Sort-Object { $rank[$_.Severity] })) {
        $it = New-Object System.Windows.Forms.ListViewItem([string]$x.Severity)
        [void]$it.SubItems.Add([string]$x.Area)
        [void]$it.SubItems.Add([string]$x.Finding)
        $fixIds = @($x.Fix | Where-Object { $_ -and $script:Actions.ContainsKey($_) })
        [void]$it.SubItems.Add((($fixIds | ForEach-Object { $script:Actions[$_].Name }) -join ', '))
        $it.Tag = $fixIds
        switch ($x.Severity) {
            'Critical' { $it.ForeColor = [System.Drawing.Color]::FromArgb(220, 60, 60) }
            'Warning'  { $it.ForeColor = [System.Drawing.Color]::FromArgb(215, 120, 0) }
            'OK'       { $it.ForeColor = [System.Drawing.Color]::FromArgb(40, 160, 90) }
        }
        if ($fixIds.Count -and ($x.Severity -eq 'Critical' -or $x.Severity -eq 'Warning')) { $it.Checked = $true }
        [void]$lvDiag.Items.Add($it)
    }
    $lvDiag.EndUpdate()
}
$btnScan.Add_Click({
    Start-Background -Script $DiagScript -Status 'Running Smart Diagnostics...' -OnComplete { Show-Findings; if (Get-Command Show-Recommendations -ErrorAction SilentlyContinue) { Show-Recommendations } }
})
$btnFix.Add_Click({
    $ids = @()
    foreach ($i in $lvDiag.CheckedItems) { $ids += @($i.Tag) }
    $ids = @($ids | Where-Object { $_ } | Select-Object -Unique)
    if (-not $ids.Count) { Show-Msg 'Tick findings that have a suggested fix first (run a scan if the list is empty).'; return }
    if ($ids -notcontains 'restorepoint' -and (Confirm-YesNo 'Create a restore point first? (recommended)')) { $ids = @('restorepoint') + $ids }
    Invoke-Actions -Ids $ids -Label 'Fixing issues'
})

# ---- Task tabs (Repair / Cleanup / Network / Security) -------------------------------------
function New-ActionPage([string]$Category, [string]$Title, [string]$Intro) {
    $page = New-Ctl TabPage @{ Text = $Title; Padding = (New-Pad 8) }
    $lbl  = New-Ctl Label @{ Text = $Intro; Dock = 'Top'; Height = 26; TextAlign = 'MiddleLeft' }
    $lv   = New-Ctl ListView @{ View = 'Details'; CheckBoxes = $true; FullRowSelect = $true; Dock = 'Fill'; HideSelection = $false; MultiSelect = $false }
    [void]$lv.Columns.Add('Task', 290); [void]$lv.Columns.Add('What it does', 720)
    foreach ($id in $script:ActionOrder) {
        $a = $script:Actions[$id]
        if ($a.Category -ne $Category) { continue }
        $name = $a.Name
        if ($a.Warning) { $name += '  (!)' }
        if ($a.Reboot)  { $name += '  (restart)' }
        $it = New-Object System.Windows.Forms.ListViewItem($name)
        [void]$it.SubItems.Add($a.Desc)
        $it.Tag = $id
        [void]$lv.Items.Add($it)
    }
    $preview = New-Ctl TextBox @{ Multiline = $true; ReadOnly = $true; Dock = 'Fill'; Font = $Mono; ScrollBars = 'Vertical'; Text = 'Select a task to see exactly what it runs.' }
    $lv.Tag = $preview
    $lv.Add_SelectedIndexChanged({
        if ($this.SelectedItems.Count -eq 0) { return }
        $a = $script:Actions[$this.SelectedItems[0].Tag]
        $t = ''
        if ($a.Desc) { $t += 'What it does: ' + $a.Desc + "`r`n`r`n" }
        $t += 'Runs: ' + $a.Preview
        if ($a.Warning) { $t += "`r`nNOTE: " + $a.Warning }
        if ($a.Reboot)  { $t += "`r`nA restart is needed to finish this task." }
        $this.Tag.Text = $t
    })
    # Button bar sits in its own panel directly under the task list, so "Run" is always visible.
    $btns = New-Ctl FlowLayoutPanel @{ Dock = 'Top'; Height = 42; Padding = (New-Pad 0, 6, 0, 0) }
    $run  = New-Ctl Button @{ Text = 'Run checked tasks'; Width = 170; Height = 30; Tag = $lv }
    $all  = New-Ctl Button @{ Text = 'Check all'; Width = 100; Height = 30; Tag = $lv }
    $none = New-Ctl Button @{ Text = 'Check none'; Width = 100; Height = 30; Tag = $lv }
    $run.Add_Click({ Invoke-Actions -Ids @($this.Tag.CheckedItems | ForEach-Object { [string]$_.Tag }) -Label 'Running tasks' })
    $all.Add_Click({ foreach ($x in $this.Tag.Items) { $x.Checked = $true } })
    $none.Add_Click({ foreach ($x in $this.Tag.Items) { $x.Checked = $false } })
    $btns.Controls.AddRange([System.Windows.Forms.Control[]]@($run, $all, $none))
    $bottomBar = New-Ctl Panel @{ Dock = 'Bottom'; Height = 122 }
    $bottomBar.Controls.Add($preview)
    $bottomBar.Controls.Add($btns)
    $page.Controls.Add($lv); $page.Controls.Add($bottomBar); $page.Controls.Add($lbl)
    $lv.BringToFront()
    return $page
}
$tabRepair   = New-ActionPage 'Repair'   'Repair'   'Built-in Windows repair tools in one place. Tick tasks and press Run - they run in a sensible order.'
$tabCleanup  = New-ActionPage 'Cleanup'  'Cleanup'  'Free up disk space safely. Sizes freed are shown in the output below.'
$tabNetwork  = New-ActionPage 'Network'  'Network'  'Diagnose and fix internet problems. Tasks marked (!) drop the connection - careful during remote sessions.'
$tabSecurity = New-ActionPage 'Security' 'Security' 'Microsoft Defender and firewall tasks.'

# ---- Profiles ------------------------------------------------------------------------------
$tabProf = New-Ctl TabPage @{ Text = 'Profiles'; Padding = (New-Pad 8) }
$gbProfList = New-Ctl GroupBox @{ Text = 'Profiles'; Dock = 'Left'; Width = 260; Padding = (New-Pad 8) }
$lbProf = New-Ctl ListBox @{ Dock = 'Fill'; IntegralHeight = $false }
$gbProfList.Controls.Add($lbProf)
$gbProfTasks = New-Ctl GroupBox @{ Text = 'Tasks in this profile (run top to bottom)'; Dock = 'Fill'; Padding = (New-Pad 8) }
$clbProf = New-Ctl CheckedListBox @{ Dock = 'Fill'; CheckOnClick = $true; IntegralHeight = $false }
$ProfileIds = New-Object System.Collections.Generic.List[string]
foreach ($id in $ActionOrder) {
    $a = $Actions[$id]
    if ($a.Category -eq 'Install') { continue }
    [void]$clbProf.Items.Add(('{0}   [{1}]' -f $a.Name, $a.Category))
    $ProfileIds.Add($id)
}
$gbProfTasks.Controls.Add($clbProf)
$profBtns = New-Ctl FlowLayoutPanel @{ Dock = 'Bottom'; Height = 44; Padding = (New-Pad 0, 8, 0, 0) }
$btnProfRun    = New-Ctl Button @{ Text = 'Run profile'; Width = 130; Height = 30 }
$btnProfSave   = New-Ctl Button @{ Text = 'Save as custom profile...'; Width = 190; Height = 30 }
$btnProfDelete = New-Ctl Button @{ Text = 'Delete custom profile'; Width = 170; Height = 30 }
$profBtns.Controls.AddRange([System.Windows.Forms.Control[]]@($btnProfRun, $btnProfSave, $btnProfDelete))
$tabProf.Controls.Add($gbProfTasks); $tabProf.Controls.Add($gbProfList); $tabProf.Controls.Add($profBtns)
$gbProfTasks.BringToFront()

function Update-ProfileList([string]$Select) {
    $script:CustomProfiles = Get-CustomProfiles
    $lbProf.Items.Clear()
    foreach ($k in $Presets.Keys) { [void]$lbProf.Items.Add($k) }
    foreach ($k in $script:CustomProfiles.Keys) { [void]$lbProf.Items.Add('[Custom] ' + $k) }
    if ($Select -and $lbProf.Items.Contains($Select)) { $lbProf.SelectedItem = $Select }
}
function Get-ProfileTasks([string]$Entry) {
    if ($Entry -like '`[Custom`] *') { return @($script:CustomProfiles[$Entry.Substring(9)]) }
    return @($Presets[$Entry])
}
$lbProf.Add_SelectedIndexChanged({
    if (-not $lbProf.SelectedItem) { return }
    $want = Get-ProfileTasks ([string]$lbProf.SelectedItem)
    for ($i = 0; $i -lt $clbProf.Items.Count; $i++) { $clbProf.SetItemChecked($i, ($want -contains $ProfileIds[$i])) }
})
$btnProfRun.Add_Click({
    $ids = @(); foreach ($i in $clbProf.CheckedIndices) { $ids += $ProfileIds[$i] }
    $label = if ($lbProf.SelectedItem) { 'Profile: ' + $lbProf.SelectedItem } else { 'Running profile' }
    Invoke-Actions -Ids $ids -Label $label
})
$btnProfSave.Add_Click({
    $ids = @(); foreach ($i in $clbProf.CheckedIndices) { $ids += $ProfileIds[$i] }
    if (-not $ids.Count) { Show-Msg 'Tick the tasks you want in the profile first.'; return }
    $name = [Microsoft.VisualBasic.Interaction]::InputBox('Name for this profile:', 'Save profile', '')
    if (-not $name.Trim()) { return }
    $p = Get-CustomProfiles; $p[$name.Trim()] = $ids; Save-CustomProfiles $p
    Update-ProfileList ('[Custom] ' + $name.Trim())
    Write-Ui ('Saved custom profile "{0}".' -f $name.Trim()) 'OK'
})
$btnProfDelete.Add_Click({
    $sel = [string]$lbProf.SelectedItem
    if ($sel -notlike '`[Custom`] *') { Show-Msg 'Select a custom profile to delete (built-in profiles cannot be deleted).'; return }
    $name = $sel.Substring(9)
    if (-not (Confirm-YesNo ('Delete the profile "{0}"?' -f $name))) { return }
    $p = Get-CustomProfiles; $p.Remove($name); Save-CustomProfiles $p
    Update-ProfileList
})
Update-ProfileList 'Quick Tune-up'

# ---- Report --------------------------------------------------------------------------------
$tabReport = New-Ctl TabPage @{ Text = 'Report'; Padding = (New-Pad 12) }
$tlRep = New-Ctl TableLayoutPanel @{ Dock = 'Top'; ColumnCount = 2; Height = 300 }
[void]$tlRep.ColumnStyles.Add((New-Object System.Windows.Forms.ColumnStyle([System.Windows.Forms.SizeType]::Absolute, 140)))
[void]$tlRep.ColumnStyles.Add((New-Object System.Windows.Forms.ColumnStyle([System.Windows.Forms.SizeType]::Percent, 100)))
$txtRepName  = New-Ctl TextBox @{ Width = 420 }
$txtNotes    = New-Ctl TextBox @{ Multiline = $true; ScrollBars = 'Vertical'; Width = 640; Height = 120 }
$chkApps     = New-Ctl CheckBox @{ Text = 'Include installed programs'; AutoSize = $true; Checked = $true }
$chkFind     = New-Ctl CheckBox @{ Text = 'Include Smart Diagnostics findings (run a scan first)'; AutoSize = $true; Checked = $true }
$chkWork     = New-Ctl CheckBox @{ Text = 'Include work performed this session'; AutoSize = $true; Checked = $true }
$lblRepNameHint = New-Ctl Label @{ Text = 'e.g. "Intake diagnostic", "After virus cleanup", "Post-repair" - becomes part of the file name so you can tell reports apart in the upload list.'; AutoSize = $true }
$lblRepNameHint.Font = New-Object System.Drawing.Font($Font.FontFamily, 8)
$lblRepWho = New-Ctl Label @{ Text = 'Customer, Ticket and Technician come from the bar at the top of the window.'; AutoSize = $true }
$lblRepWho.Font = New-Object System.Drawing.Font($Font.FontFamily, 8)
$rowsRep = @(
    @('Report name', $txtRepName), @('', $lblRepNameHint),
    @('Notes', $txtNotes),
    @('', $chkWork), @('', $chkFind), @('', $chkApps), @('', $lblRepWho)
)
$row = 0
foreach ($rr in $rowsRep) {
    $tlRep.Controls.Add((New-Ctl Label @{ Text = $rr[0]; AutoSize = $true; Padding = (New-Pad 0, 6, 0, 0) }), 0, $row)
    $tlRep.Controls.Add($rr[1], 1, $row)
    $row++
}
$repBtns = New-Ctl FlowLayoutPanel @{ Dock = 'Top'; Height = 44; Padding = (New-Pad 136, 6, 0, 0) }
$btnReport     = New-Ctl Button @{ Text = 'Generate report'; Width = 150; Height = 30 }
$btnReportDir  = New-Ctl Button @{ Text = 'Open reports folder'; Width = 160; Height = 30 }
$repBtns.Controls.AddRange([System.Windows.Forms.Control[]]@($btnReport, $btnReportDir))
$lblRepInfo = New-Ctl Label @{ Dock = 'Top'; Height = 40; Text = 'Creates a branded HTML report (company name and phone come from Settings). Open it in a browser to print or save as PDF.' }
$tabReport.Controls.Add($lblRepInfo); $tabReport.Controls.Add($repBtns); $tabReport.Controls.Add($tlRep)

function Invoke-GenerateReport {
    $info = @{
        ReportName = $txtRepName.Text.Trim()
        Customer = $txtCustomer.Text.Trim(); Ticket = $txtTicket.Text.Trim(); Tech = $txtTech.Text.Trim(); Notes = $txtNotes.Text.Trim()
        CompanyName = $script:Settings.CompanyName; CompanyPhone = $script:Settings.CompanyPhone; Website = $script:Settings.CompanyWebsite
    }
    $vars = @{
        Info = $info; IncludeApps = $chkApps.Checked; IncludeFindings = $chkFind.Checked; IncludeWork = $chkWork.Checked
        Findings = $Sync.Findings; ReportDir = $ReportDir; RemoteScan = $Sync.RemoteScan; PcrtFolder = $script:Settings.PcrtFolder
        BackupRecord = @($Sync.BackupRecord.ToArray()); SpeedTests = @($Sync.SpeedTests.ToArray()); Logo = (Get-LogoDataUri)
    }
    Start-Background -Script $ReportScript -Vars $vars -Status 'Building report...' -OnComplete {
        if ($Sync.ReportPath -and (Test-Path -LiteralPath $Sync.ReportPath)) { Start-Process $Sync.ReportPath }
    }
}
$btnReport.Add_Click({ Invoke-GenerateReport })
$btnReportDir.Add_Click({ Initialize-DataDirs; Start-Process explorer.exe $ReportDir })
$btnDashReport.Add_Click({ Show-Tab $tabReport })
$btnDashDiag.Add_Click({ Show-Tab $tabDiag; $btnScan.PerformClick() })
$btnDashTune.Add_Click({ Invoke-Actions -Ids $Presets['Quick Tune-up'] -Label 'Quick Tune-up' })

function Start-DeployRemote {
    $vars = @{ Installer = $script:Settings.RemoteInstaller; InstArgs = $script:Settings.RemoteArgs; LaunchExe = $script:Settings.RemoteLaunchExe }
    if (-not $vars.Installer -and -not $vars.LaunchExe) {
        Show-Msg "No remote support agent is set up yet.`r`n`r`nOpen Settings > Remote support and paste the URL or file path of your ScreenConnect access installer (and, optionally, the path to the installed client to launch)."
        Show-Tab $tabSet; return
    }
    Start-Background -Script $script:DeployRemoteScript -Vars $vars -Status 'Deploying remote support agent...'
}
$btnDashDeploy.Add_Click({ Start-DeployRemote })
$btnDashRemote.Add_Click({ Show-Tab $tabRemote; $btnRemoteScan.PerformClick() })

# ---- Tools ---------------------------------------------------------------------------------
$tabTools = New-Ctl TabPage @{ Text = 'Tools'; Padding = (New-Pad 8); AutoScroll = $true }
$gbWin = New-Ctl GroupBox @{ Text = 'Windows tools'; Dock = 'Top'; Height = 190; Padding = (New-Pad 8) }
$flWin = New-Ctl FlowLayoutPanel @{ Dock = 'Fill'; AutoScroll = $true }
$WinTools = @(
    @('Task Manager', 'taskmgr.exe', ''), @('Device Manager', 'devmgmt.msc', ''), @('Event Viewer', 'eventvwr.msc', ''),
    @('Services', 'services.msc', ''), @('Disk Management', 'diskmgmt.msc', ''), @('Computer Management', 'compmgmt.msc', ''),
    @('Reliability Monitor', 'perfmon.exe', '/rel'), @('Resource Monitor', 'resmon.exe', ''), @('System Information', 'msinfo32.exe', ''),
    @('System Configuration', 'msconfig.exe', ''), @('Registry Editor', 'regedit.exe', ''), @('Programs and Features', 'appwiz.cpl', ''),
    @('Network Connections', 'ncpa.cpl', ''), @('Power Options', 'powercfg.cpl', ''), @('Disk Cleanup', 'cleanmgr.exe', ''),
    @('System Restore', 'rstrui.exe', ''), @('Memory Diagnostic', 'mdsched.exe', ''), @('Windows Update', 'ms-settings:windowsupdate', ''),
    @('Troubleshooters', 'ms-settings:troubleshoot', ''), @('Startup Apps', 'ms-settings:startupapps', ''), @('Windows Security', 'windowsdefender:', ''),
    @('Admin Command Prompt', 'cmd.exe', ''), @('Admin PowerShell', 'powershell.exe', '-NoExit -NoProfile')
)
foreach ($t in $WinTools) {
    $b = New-Ctl Button @{ Text = $t[0]; Width = 170; Height = 30; Tag = $t }
    $b.Add_Click({
        $t = $this.Tag
        try {
            if ($t[2]) { Start-Process -FilePath $t[1] -ArgumentList $t[2] } else { Start-Process -FilePath $t[1] }
            Write-Ui ('Opened {0}' -f $t[0])
        } catch { Show-Msg ('Could not open {0}: {1}' -f $t[0], $_.Exception.Message) 'Warning' }
    })
    $flWin.Controls.Add($b)
}
$btnBattery = New-Ctl Button @{ Text = 'Battery report'; Width = 170; Height = 30 }
$btnBattery.Add_Click({
    Initialize-DataDirs
    $p = Join-Path $ReportDir ('battery-{0}-{1:yyyyMMdd-HHmm}.html' -f $env:COMPUTERNAME, (Get-Date))
    Start-Process powercfg.exe -ArgumentList "/batteryreport /output `"$p`"" -Wait -WindowStyle Hidden
    if (Test-Path -LiteralPath $p) { Start-Process $p } else { Show-Msg 'No battery found on this PC.' }
})
$flWin.Controls.Add($btnBattery)
$btnMemTest = New-Ctl Button @{ Text = 'Test RAM (memory)'; Width = 170; Height = 30 }
$btnMemTest.Add_Click({
    if (-not (Confirm-YesNo ("Run the Windows Memory Diagnostic (built-in RAM test)?" + [Environment]::NewLine + [Environment]::NewLine + "It needs a restart to run - Windows will ask to restart now or on the next boot, then test the RAM and report any faults after it reboots. Save open work first." + [Environment]::NewLine + [Environment]::NewLine + "For a deeper test, use MemTest86 (bootable) from the Toolbox tab."))) { return }
    try { Start-Process mdsched.exe; Write-Ui 'Opened Windows Memory Diagnostic - choose when to restart and run the RAM test.' 'OK' }
    catch { Write-Ui ('Could not start the memory test: {0}' -f $_.Exception.Message) 'WARN' }
})
$flWin.Controls.Add($btnMemTest)
$gbWin.Controls.Add($flWin)

$gbWinget = New-Ctl GroupBox @{ Text = 'Install popular tech tools (winget)'; Dock = 'Top'; Height = 86; Padding = (New-Pad 8) }
$flWinget = New-Ctl FlowLayoutPanel @{ Dock = 'Fill'; AutoScroll = $true }
foreach ($appName in $WingetApps.Keys) {
    $b = New-Ctl Button @{ Text = $appName; Width = 140; Height = 30; Tag = ('inst_' + $WingetApps[$appName][0]) }
    $b.Add_Click({ Invoke-Actions -Ids @([string]$this.Tag) -Label ('Installing ' + $this.Text) })
    $flWinget.Controls.Add($b)
}
$gbWinget.Controls.Add($flWinget)

$gbMine = New-Ctl GroupBox @{ Text = 'My tools (your own utilities - portable apps, scripts, USB tools)'; Dock = 'Fill'; Padding = (New-Pad 8) }
$lvMine = New-Ctl ListView @{ View = 'Details'; Dock = 'Fill'; FullRowSelect = $true; MultiSelect = $false }
[void]$lvMine.Columns.Add('Name', 200); [void]$lvMine.Columns.Add('Path', 520); [void]$lvMine.Columns.Add('Arguments', 200)
$mineBtns = New-Ctl FlowLayoutPanel @{ Dock = 'Bottom'; Height = 42; Padding = (New-Pad 0, 6, 0, 0) }
$btnMineLaunch = New-Ctl Button @{ Text = 'Launch'; Width = 100; Height = 30 }
$btnMineAdd    = New-Ctl Button @{ Text = 'Add...'; Width = 100; Height = 30 }
$btnMineRemove = New-Ctl Button @{ Text = 'Remove'; Width = 100; Height = 30 }
$mineBtns.Controls.AddRange([System.Windows.Forms.Control[]]@($btnMineLaunch, $btnMineAdd, $btnMineRemove))
$gbMine.Controls.Add($lvMine); $gbMine.Controls.Add($mineBtns); $lvMine.BringToFront()

function Update-MyTools {
    $lvMine.Items.Clear()
    foreach ($t in @($script:Settings.Tools)) {
        $it = New-Object System.Windows.Forms.ListViewItem([string]$t.Name)
        [void]$it.SubItems.Add([string]$t.Path); [void]$it.SubItems.Add([string]$t.Args)
        $it.Tag = $t
        [void]$lvMine.Items.Add($it)
    }
}
function Start-MyTool {
    if ($lvMine.SelectedItems.Count -eq 0) { Show-Msg 'Select a tool first.'; return }
    $t = $lvMine.SelectedItems[0].Tag
    if (-not (Test-Path -LiteralPath $t.Path)) { Show-Msg ('Not found: {0}' -f $t.Path) 'Warning'; return }
    try {
        if ($t.Path -like '*.ps1') {
            Start-Process powershell.exe -ArgumentList ('-NoProfile -ExecutionPolicy Bypass -NoExit -File "{0}" {1}' -f $t.Path, $t.Args)
        } elseif ($t.Args) {
            Start-Process -FilePath $t.Path -ArgumentList $t.Args -WorkingDirectory (Split-Path $t.Path)
        } else {
            Start-Process -FilePath $t.Path -WorkingDirectory (Split-Path $t.Path)
        }
        Write-Ui ('Launched {0}' -f $t.Name)
    } catch { Show-Msg ('Could not launch: {0}' -f $_.Exception.Message) 'Warning' }
}
$btnMineLaunch.Add_Click({ Start-MyTool })
$lvMine.Add_DoubleClick({ Start-MyTool })
$btnMineAdd.Add_Click({
    $dlg = New-Ctl OpenFileDialog @{ Filter = 'Programs and scripts|*.exe;*.bat;*.cmd;*.ps1;*.msc;*.lnk|All files|*.*'; Title = 'Choose a tool' }
    if ($dlg.ShowDialog($form) -ne 'OK') { return }
    $defName = [IO.Path]::GetFileNameWithoutExtension($dlg.FileName)
    $name = [Microsoft.VisualBasic.Interaction]::InputBox('Display name:', 'Add tool', $defName)
    if (-not $name.Trim()) { return }
    $toolArgs = [Microsoft.VisualBasic.Interaction]::InputBox('Command-line arguments (optional):', 'Add tool', '')
    $script:Settings.Tools = @($script:Settings.Tools) + [pscustomobject]@{ Name = $name.Trim(); Path = $dlg.FileName; Args = $toolArgs }
    Save-Settings; Update-MyTools
})
$btnMineRemove.Add_Click({
    if ($lvMine.SelectedItems.Count -eq 0) { return }
    $sel = $lvMine.SelectedItems[0].Tag
    $script:Settings.Tools = @($script:Settings.Tools | Where-Object { -not ($_.Name -eq $sel.Name -and $_.Path -eq $sel.Path) })
    Save-Settings; Update-MyTools
})
Update-MyTools
$tabTools.Controls.Add($gbMine); $tabTools.Controls.Add($gbWinget); $tabTools.Controls.Add($gbWin)
$gbMine.BringToFront()

# ---- Settings ------------------------------------------------------------------------------
$tabSet = New-Ctl TabPage @{ Text = 'Settings'; Padding = (New-Pad 12); AutoScroll = $true }
$tlSet = New-Ctl TableLayoutPanel @{ Dock = 'Top'; ColumnCount = 2; AutoSize = $true; AutoSizeMode = 'GrowAndShrink' }
[void]$tlSet.ColumnStyles.Add((New-Object System.Windows.Forms.ColumnStyle([System.Windows.Forms.SizeType]::Absolute, 180)))
[void]$tlSet.ColumnStyles.Add((New-Object System.Windows.Forms.ColumnStyle([System.Windows.Forms.SizeType]::Percent, 100)))
$cbTheme = New-Ctl ComboBox @{ DropDownStyle = 'DropDownList'; Width = 160 }
[void]$cbTheme.Items.AddRange(@('Light', 'Dark')); $cbTheme.SelectedItem = $Settings.Theme
$txtCompany = New-Ctl TextBox @{ Width = 360; Text = $Settings.CompanyName }
$txtPhone   = New-Ctl TextBox @{ Width = 220; Text = $Settings.CompanyPhone }
$txtWeb     = New-Ctl TextBox @{ Width = 300; Text = $Settings.CompanyWebsite }
$txtDefTech = New-Ctl TextBox @{ Width = 220; Text = $Settings.TechName }
$chkConfirm = New-Ctl CheckBox @{ Text = 'Show the commands and ask before running tasks'; AutoSize = $true; Checked = [bool]$Settings.ConfirmCommands }
$txtRemoteInst = New-Ctl TextBox @{ Width = 460; Text = $Settings.RemoteInstaller }
$txtRemoteArgs = New-Ctl TextBox @{ Width = 220; Text = $Settings.RemoteArgs }
$txtRemoteExe  = New-Ctl TextBox @{ Width = 460; Text = $Settings.RemoteLaunchExe }
$txtPcrt       = New-Ctl TextBox @{ Width = 460; Text = $Settings.PcrtFolder }
$txtFab        = New-Ctl TextBox @{ Width = 460; Text = $Settings.FabPath }
$txtMsp        = New-Ctl TextBox @{ Width = 460; Text = $Settings.Msp360Path }
$txtLogo       = New-Ctl TextBox @{ Width = 460; Text = $Settings.LogoPath }
$txtAttachUrl  = New-Ctl TextBox @{ Width = 460; Text = $Settings.AttachUrl }
$txtHash       = New-Ctl TextBox @{ Width = 460; Text = $Settings.StoreHash; UseSystemPasswordChar = $true }

# Wrap an input with a plain-language help line so each setting explains itself.
function New-SetCell($ctrl, [string]$help) {
    $p = New-Ctl FlowLayoutPanel @{ FlowDirection = 'TopDown'; AutoSize = $true; AutoSizeMode = 'GrowAndShrink'; WrapContents = $false; Margin = (New-Pad 0, 2, 0, 8) }
    $p.Controls.Add($ctrl)
    $h = New-Ctl Label @{ Text = $help; AutoSize = $true; MaximumSize = (New-Object System.Drawing.Size(600, 0)); Margin = (New-Pad 2, 1, 0, 0) }
    $h.Font = New-Object System.Drawing.Font($Font.FontFamily, 8)
    $p.Controls.Add($h)
    return $p
}
function New-SetHeader([string]$text) {
    $l = New-Ctl Label @{ Text = $text; AutoSize = $true; Padding = (New-Pad 0, 12, 0, 2) }
    $l.Font = New-Object System.Drawing.Font($Font, [System.Drawing.FontStyle]::Bold)
    return $l
}
$rowsSet = @(
    @((New-SetHeader 'Appearance'), $null),
    @('Theme', (New-SetCell $cbTheme 'Light or dark colours for the BenchKit window.')),
    @((New-SetHeader 'Your shop (printed on reports and the customer info sheet)'), $null),
    @('Company name', (New-SetCell $txtCompany 'Your shop name. Appears in the window title and as the heading on customer reports and info sheets.')),
    @('Company phone', (New-SetCell $txtPhone 'Shown on the customer report so they know who to call. Leave blank to omit.')),
    @('Website', (New-SetCell $txtWeb 'e.g. cybrac.com - shown in the app header and on every report/info sheet so the work is clearly from you.')),
    @('Default technician', (New-SetCell $txtDefTech 'Your name. Pre-fills the Technician box on the Report and Repair Tracker tabs.')),
    @('Logo image', (New-SetCell $txtLogo 'Optional. A PNG/JPG of your logo (a wide logo works best). Shows in the app header and at the top of customer reports and info sheets. Use "Browse logo" below to pick it.')),
    @((New-SetHeader "Remote support (the Dashboard's 'Deploy remote support' button)"), $null),
    @('Remote agent installer', (New-SetCell $txtRemoteInst 'Path or URL to your ScreenConnect/remote access installer. Deploy runs this to put your agent on the PC. e.g. \\server\share\ConnectWiseControl.ClientSetup.msi  or  https://yourco.screenconnect.com/Bin/...msi')),
    @('Installer silent args', (New-SetCell $txtRemoteArgs 'Switches that make that installer run silently. Default /qn is for an .msi. Clear it if your installer needs none.')),
    @('Remote client to launch', (New-SetCell $txtRemoteExe 'Optional. Full path to the already-installed remote client .exe, so Deploy just launches it when the agent is already present. e.g. "C:\Program Files (x86)\ScreenConnect Client (xxxx)\ScreenConnect.ClientService.exe"')),
    @((New-SetHeader 'Integrations'), $null),
    @('PCRT report folder', (New-SetCell $txtPcrt 'Optional. A local or network folder where the customer report is ALSO saved, so it can be attached to a PCRT ticket. Leave blank to skip. (The Repair Tracker tab is the other, no-folder way to send reports.)')),
    @("Fab's AutoBackup (.exe)", (New-SetCell $txtFab "Optional. Full path to Fab's AutoBackup if you use it; the Backup tab can launch it. Leave blank if you don't.")),
    @('MSP360 Backup (.exe)', (New-SetCell $txtMsp "Optional. Full path to your MSP360 / Online Backup client. The Backup tab's 'Launch MSP360' button opens it. Leave blank to auto-detect or browse the first time you use it.")),
    @('HTML attach URL', (New-SetCell $txtAttachUrl "Where the 'Attach selected as HTML' button on the Repair Tracker tab posts report files (your benchkit_attach.php). Leave default unless your tracker lives elsewhere.")),
    @('Store hash', (New-SetCell $txtHash "Your PCRT store hash - needed only for HTML attachments. From the tracker: Admin > Settings > Integrations. Treat it like a password; it is stored masked on this PC.")),
    @((New-SetHeader 'Behaviour'), $null),
    @('', (New-SetCell $chkConfirm 'When ticked, BenchKit shows the exact commands and asks before running repair/cleanup tasks. Untick for faster, no-prompt runs.'))
)
$row = 0
foreach ($rr in $rowsSet) {
    if ($null -eq $rr[1]) {
        $tlSet.Controls.Add($rr[0], 0, $row)
        $tlSet.SetColumnSpan($rr[0], 2)
    } else {
        $tlSet.Controls.Add((New-Ctl Label @{ Text = $rr[0]; AutoSize = $true; Padding = (New-Pad 0, 6, 0, 0) }), 0, $row)
        $tlSet.Controls.Add($rr[1], 1, $row)
    }
    $row++
}
$setBtns = New-Ctl FlowLayoutPanel @{ Dock = 'Top'; Height = 44; Padding = (New-Pad 166, 6, 0, 0) }
$btnSetSave  = New-Ctl Button @{ Text = 'Save settings'; Width = 130; Height = 30 }
$btnSetData  = New-Ctl Button @{ Text = 'Open data folder'; Width = 140; Height = 30 }
$btnSetReset = New-Ctl Button @{ Text = 'Reset to defaults...'; Width = 160; Height = 30 }
$btnSetPass  = New-Ctl Button @{ Text = 'Set launch passcode...'; Width = 170; Height = 30 }
$btnLogoBrowse = New-Ctl Button @{ Text = 'Browse logo...'; Width = 130; Height = 30 }
$btnLogoBrowse.Add_Click({
    $dlg = New-Ctl OpenFileDialog @{ Filter = 'Images|*.png;*.jpg;*.jpeg;*.gif;*.bmp|All files|*.*'; Title = 'Choose your logo image' }
    if ($dlg.ShowDialog($form) -eq 'OK') { $txtLogo.Text = $dlg.FileName }
})
$btnSetPass.Add_Click({
    $p1 = Read-Secret 'Set launch passcode' 'Enter a new passcode:'
    if ($null -eq $p1) { return }
    if ($p1 -eq '') { Show-Msg 'To turn the passcode OFF, set $LaunchPassHash = '''' (empty) near the top of BenchKit.ps1, then re-save/re-host the script.'; return }
    $p2 = Read-Secret 'Set launch passcode' 'Re-enter the passcode to confirm:'
    if ($null -eq $p2) { return }
    if ($p1 -ne $p2) { Show-Msg 'The passcodes did not match - nothing changed.'; return }
    $hash = Get-TextSha256 $p1
    try { Set-Clipboard -Value $hash -ErrorAction Stop; $copied = ' (copied to clipboard)' } catch { $copied = '' }
    Show-Msg ("New passcode hash{0}:`r`n`r`n{1}`r`n`r`nTo apply it everywhere, open BenchKit.ps1 and replace the hash on the `$LaunchPassHash line (near the top) with the value above, then re-save / re-host the script. The new passcode takes effect next launch." -f $copied, $hash)
})
$setBtns.Controls.AddRange([System.Windows.Forms.Control[]]@($btnSetSave, $btnLogoBrowse, $btnSetData, $btnSetPass, $btnSetReset))
$lblAbout = New-Ctl Label @{ Dock = 'Top'; Height = 90; Text = ("{0} {1}`r`nData folder: {2}`r`nReset to defaults removes all {0} settings, custom profiles, logs and reports from this PC (handy before handing a PC back, or before deleting the app). Windows changes made by tasks are not undone - use System Restore for that." -f $AppName, $AppVersion, $DataDir) }
$tabSet.Controls.Add($lblAbout); $tabSet.Controls.Add($setBtns); $tabSet.Controls.Add($tlSet)

$btnSetSave.Add_Click({
    $script:Settings.Theme           = [string]$cbTheme.SelectedItem
    $script:Settings.CompanyName     = $txtCompany.Text.Trim()
    $script:Settings.CompanyPhone    = $txtPhone.Text.Trim()
    $script:Settings.CompanyWebsite  = $txtWeb.Text.Trim()
    $script:Settings.TechName        = $txtDefTech.Text.Trim()
    $script:Settings.ConfirmCommands = $chkConfirm.Checked
    $script:Settings.RemoteInstaller = $txtRemoteInst.Text.Trim()
    $script:Settings.RemoteArgs      = $txtRemoteArgs.Text.Trim()
    $script:Settings.RemoteLaunchExe = $txtRemoteExe.Text.Trim()
    $script:Settings.PcrtFolder      = $txtPcrt.Text.Trim()
    $script:Settings.FabPath         = $txtFab.Text.Trim()
    $script:Settings.Msp360Path      = $txtMsp.Text.Trim()
    $script:Settings.LogoPath        = $txtLogo.Text.Trim()
    $script:Settings.AttachUrl       = $txtAttachUrl.Text.Trim()
    $script:Settings.StoreHash       = $txtHash.Text.Trim()
    Save-Settings
    Set-Theme $script:Settings.Theme
    Set-Brand
    if (-not $txtTech.Text) { $txtTech.Text = $script:Settings.TechName }
    Write-Ui 'Settings saved.' 'OK'
})
$btnSetData.Add_Click({ Initialize-DataDirs; Start-Process explorer.exe $DataDir })
$btnSetReset.Add_Click({
    if ($Sync.Busy) { Show-Msg 'Wait for the running task to finish first.'; return }
    if (-not (Confirm-YesNo ("Remove all {0} settings, custom profiles, logs and reports from this PC?`r`n`r`n{1}" -f $AppName, $DataDir))) { return }
    Remove-Item -LiteralPath $DataDir -Recurse -Force -ErrorAction SilentlyContinue
    Initialize-DataDirs
    $script:Settings = Get-Settings
    $cbTheme.SelectedItem = $script:Settings.Theme; $txtCompany.Text = ''; $txtPhone.Text = ''; $txtWeb.Text = ''
    $txtDefTech.Text = $script:Settings.TechName; $chkConfirm.Checked = $true
    $txtRemoteInst.Text = ''; $txtRemoteArgs.Text = $script:Settings.RemoteArgs; $txtRemoteExe.Text = ''; $txtPcrt.Text = ''; $txtFab.Text = ''; $txtMsp.Text = ''; $txtLogo.Text = ''; $txtAttachUrl.Text = $script:Settings.AttachUrl; $txtHash.Text = ''
    Set-Theme $script:Settings.Theme; Set-Brand
    Update-MyTools; Update-ProfileList 'Quick Tune-up'
    Write-Ui 'Reset to defaults complete.' 'OK'
})

# ---- Security Scan (remote-access tools) ---------------------------------------------------
$tabRemote = New-Ctl TabPage @{ Text = 'Security Scan'; Padding = (New-Pad 8) }
$remTop = New-Ctl FlowLayoutPanel @{ Dock = 'Top'; Height = 44; WrapContents = $false }
$btnRemoteFull   = New-Ctl Button @{ Text = 'Scan && build report'; Width = 170; Height = 30 }
$btnRemoteScan   = New-Ctl Button @{ Text = 'Scan only'; Width = 110; Height = 30 }
$btnRemoteReport = New-Ctl Button @{ Text = 'Show in report'; Width = 140; Height = 30 }
$lblRemote = New-Ctl Label @{ Text = 'Finds remote-access and screen-sharing tools (installed, running, as a service, or a scheduled task). Confirm each one with the customer and remove anything they do not recognise.'; AutoSize = $true; Padding = (New-Pad 10, 8, 0, 0) }
$remTop.Controls.AddRange([System.Windows.Forms.Control[]]@($btnRemoteFull, $btnRemoteScan, $btnRemoteReport, $lblRemote))
$lvRemote = New-Ctl ListView @{ View = 'Details'; Dock = 'Fill'; FullRowSelect = $true }
[void]$lvRemote.Columns.Add('Severity', 80); [void]$lvRemote.Columns.Add('Tool', 230); [void]$lvRemote.Columns.Add('Found as', 140); [void]$lvRemote.Columns.Add('Detail', 560)
$tabRemote.Controls.Add($lvRemote); $tabRemote.Controls.Add($remTop); $lvRemote.BringToFront()

function Show-RemoteScan {
    $lvRemote.BeginUpdate(); $lvRemote.Items.Clear()
    foreach ($x in @($Sync.RemoteScan)) {
        if (-not $x) { continue }
        $it = New-Object System.Windows.Forms.ListViewItem([string]$x.Severity)
        [void]$it.SubItems.Add([string]$x.Name); [void]$it.SubItems.Add([string]$x.Evidence); [void]$it.SubItems.Add([string]$x.Detail)
        $it.ForeColor = [System.Drawing.Color]::FromArgb(215, 120, 0)
        [void]$lvRemote.Items.Add($it)
    }
    if ($lvRemote.Items.Count -eq 0) {
        $it = New-Object System.Windows.Forms.ListViewItem('OK'); [void]$it.SubItems.Add('None found'); [void]$it.SubItems.Add(''); [void]$it.SubItems.Add('No remote-access software detected on this PC.')
        $it.ForeColor = [System.Drawing.Color]::FromArgb(40, 160, 90); [void]$lvRemote.Items.Add($it)
    }
    $lvRemote.EndUpdate()
}
$btnRemoteScan.Add_Click({ Start-Background -Script $RemoteScanScript -Status 'Scanning for remote-access software...' -OnComplete { Show-RemoteScan } })
$btnRemoteFull.Add_Click({
    if ($Sync.Busy) { Show-Msg 'Another task is still running. Wait for it to finish, or press Stop.'; return }
    # One click: scan for remote-access software, then build the customer report (which includes the results) and open it.
    Start-Background -Script $RemoteScanScript -Status 'Scanning for remote-access software...' -OnComplete {
        Show-RemoteScan
        Invoke-GenerateReport
    }
})
$btnRemoteReport.Add_Click({
    if (-not @($Sync.RemoteScan).Count) { Show-Msg 'Run a scan first - then it will be included when you generate the customer report.'; return }
    Show-Tab $tabReport
    Show-Msg 'The remote-access results are ready. Press "Generate report" and they will be included.'
})

# ---- Info Recovery -------------------------------------------------------------------------
$tabInfo = New-Ctl TabPage @{ Text = 'Info Recovery'; Padding = (New-Pad 12) }
$infoFlow = New-Ctl FlowLayoutPanel @{ Dock = 'Fill'; FlowDirection = 'TopDown'; WrapContents = $false; AutoScroll = $true }
$lblInfo = New-Ctl Label @{ AutoSize = $true; MaximumSize = [System.Drawing.Size]::new(900, 0); Margin = (New-Pad 3, 3, 3, 10)
    Text = "Recover the customer's own information from this PC and save it to a confidential sheet you can keep with the ticket. Uses the Customer / Ticket fields from the Report tab." }
$chkWifi = New-Ctl CheckBox @{ Text = 'Saved Wi-Fi network passwords'; AutoSize = $true; Checked = $true; Margin = (New-Pad 3) }
$chkKey  = New-Ctl CheckBox @{ Text = 'Windows product key (recoverable OEM key only)'; AutoSize = $true; Checked = $true; Margin = (New-Pad 3) }
$chkBL   = New-Ctl CheckBox @{ Text = 'BitLocker recovery key (back up so the customer is not locked out later)'; AutoSize = $true; Margin = (New-Pad 3) }
$chkBLConsent = New-Ctl CheckBox @{ Text = 'The customer has consented to us saving their BitLocker recovery key'; AutoSize = $true; Margin = (New-Pad 24, 0, 3, 8) }
$lblInfoNote = New-Ctl Label @{ AutoSize = $true; MaximumSize = [System.Drawing.Size]::new(900, 0); ForeColor = [System.Drawing.Color]::FromArgb(150, 90, 0); Margin = (New-Pad 3, 3, 3, 10)
    Text = "Note: saved browser and email passwords are deliberately not collected here. The customer can export those themselves from their browser while signed in as themselves (e.g. Chrome > Settings > Passwords > Export), which keeps that behind their own login." }
$infoBtns = New-Ctl FlowLayoutPanel @{ AutoSize = $true; Margin = (New-Pad 3) }
$btnInfoRun = New-Ctl Button @{ Text = 'Recover and save sheet'; Width = 180; Height = 30 }
$btnInfoDir = New-Ctl Button @{ Text = 'Open sheet folder'; Width = 150; Height = 30 }
$infoBtns.Controls.AddRange([System.Windows.Forms.Control[]]@($btnInfoRun, $btnInfoDir))
$infoFlow.Controls.AddRange([System.Windows.Forms.Control[]]@($lblInfo, $chkWifi, $chkKey, $chkBL, $chkBLConsent, $lblInfoNote, $infoBtns))
$tabInfo.Controls.Add($infoFlow)

$btnInfoRun.Add_Click({
    $recover = @()
    if ($chkWifi.Checked) { $recover += 'wifi' }
    if ($chkKey.Checked)  { $recover += 'productkey' }
    if ($chkBL.Checked)   { $recover += 'bitlocker' }
    if (-not $recover.Count) { Show-Msg 'Tick at least one item to recover.'; return }
    if ($chkBL.Checked -and -not $chkBLConsent.Checked) { Show-Msg 'To include the BitLocker recovery key, tick the box confirming the customer has consented.'; return }
    $info = @{ Customer = $txtCustomer.Text.Trim(); Ticket = $txtTicket.Text.Trim(); Tech = $txtTech.Text.Trim(); CompanyName = $script:Settings.CompanyName; CompanyPhone = $script:Settings.CompanyPhone; Website = $script:Settings.CompanyWebsite }
    $vars = @{ Recover = $recover; BitlockerConsent = $chkBLConsent.Checked; Info = $info; ReportDir = $ReportDir; Logo = (Get-LogoDataUri) }
    Start-Background -Script $InfoRecoveryScript -Vars $vars -Status 'Recovering customer information...' -OnComplete {
        if ($Sync.InfoSheetPath -and (Test-Path -LiteralPath $Sync.InfoSheetPath)) { Start-Process $Sync.InfoSheetPath }
    }
})
$btnInfoDir.Add_Click({ Initialize-DataDirs; Start-Process explorer.exe $ReportDir })

# ---- Backup & Migrate ----------------------------------------------------------------------
$BackupMap = [ordered]@{
    'Documents'         = @('Documents')
    'Desktop'           = @('Desktop')
    'Pictures'          = @('Pictures')
    'Music'             = @('Music')
    'Videos'            = @('Videos')
    'Downloads'         = @('Downloads')
    'Favorites & Links' = @('Favorites', 'Links')
    'Chrome data'       = @('AppData\Local\Google\Chrome\User Data')
    'Edge data'         = @('AppData\Local\Microsoft\Edge\User Data')
    'Firefox data'      = @('AppData\Roaming\Mozilla\Firefox')
    'Outlook data'      = @('AppData\Local\Microsoft\Outlook', 'Documents\Outlook Files')
    'Thunderbird data'  = @('AppData\Roaming\Thunderbird')
}
function Add-BackupRecordLine($Source, $Dest, $Result) {
    [void]$Sync.BackupRecord.Add([pscustomobject]@{ Time = (Get-Date).ToString('yyyy-MM-dd HH:mm'); Source = $Source; Destination = $Dest; Result = $Result })
    Write-Ui ('Backup logged for report: {0} -> {1}' -f $Source, $Dest) 'OK'
}

$tabBackup = New-Ctl TabPage @{ Text = 'Backup'; Padding = (New-Pad 8); AutoScroll = $true }

$gbSrc = New-Ctl GroupBox @{ Text = '1. Source - where the files are'; Dock = 'Top'; Height = 104; Padding = (New-Pad 8, 2, 8, 2) }
$rbThisPC = New-Ctl RadioButton @{ Text = 'Users on this PC'; AutoSize = $true; Checked = $true; Location = [System.Drawing.Point]::new(12, 20) }
$rbOther  = New-Ctl RadioButton @{ Text = 'Another drive / folder (e.g. an old disk on USB)'; AutoSize = $true; Location = [System.Drawing.Point]::new(160, 20) }
$txtSrcRoot = New-Ctl TextBox @{ Width = 520; Location = [System.Drawing.Point]::new(14, 48); Text = (Join-Path $env:SystemDrive 'Users'); Enabled = $false }
$btnSrcBrowse = New-Ctl Button @{ Text = 'Browse...'; Width = 90; Height = 24; Location = [System.Drawing.Point]::new(542, 47); Enabled = $false }
$btnScanProf  = New-Ctl Button @{ Text = '1) Scan profiles'; Width = 130; Height = 24; Location = [System.Drawing.Point]::new(642, 47) }
$gbSrc.Controls.AddRange([System.Windows.Forms.Control[]]@($rbThisPC, $rbOther, $txtSrcRoot, $btnSrcBrowse, $btnScanProf))

$tlMid = New-Ctl TableLayoutPanel @{ Dock = 'Fill'; ColumnCount = 2 }
[void]$tlMid.ColumnStyles.Add((New-Object System.Windows.Forms.ColumnStyle([System.Windows.Forms.SizeType]::Percent, 62)))
[void]$tlMid.ColumnStyles.Add((New-Object System.Windows.Forms.ColumnStyle([System.Windows.Forms.SizeType]::Percent, 38)))
$gbProfiles = New-Ctl GroupBox @{ Text = '2. User profiles (tick who to back up)'; Dock = 'Fill'; Padding = (New-Pad 6) }
$lvProfiles = New-Ctl ListView @{ View = 'Details'; Dock = 'Fill'; CheckBoxes = $true; FullRowSelect = $true }
[void]$lvProfiles.Columns.Add('User', 150); [void]$lvProfiles.Columns.Add('Common data', 100); [void]$lvProfiles.Columns.Add('Location', 320)
$gbProfiles.Controls.Add($lvProfiles)
$gbCats = New-Ctl GroupBox @{ Text = '2. What to include'; Dock = 'Fill'; Padding = (New-Pad 6) }
$clbCats = New-Ctl CheckedListBox @{ Dock = 'Fill'; CheckOnClick = $true; IntegralHeight = $false }
foreach ($c in $BackupMap.Keys) { [void]$clbCats.Items.Add($c, $true) }
$gbCats.Controls.Add($clbCats)
$tlMid.Controls.Add($gbProfiles, 0, 0); $tlMid.Controls.Add($gbCats, 1, 0)

$gbDest = New-Ctl GroupBox @{ Text = '3. Destination - where to save the copy'; Dock = 'Bottom'; Height = 72; Padding = (New-Pad 8, 2, 8, 2) }
$txtDest = New-Ctl TextBox @{ Width = 620; Location = [System.Drawing.Point]::new(14, 22) }
$btnDestBrowse = New-Ctl Button @{ Text = 'Browse...'; Width = 90; Height = 24; Location = [System.Drawing.Point]::new(642, 21) }
$gbDest.Controls.AddRange([System.Windows.Forms.Control[]]@($txtDest, $btnDestBrowse))

$bkBtns = New-Ctl FlowLayoutPanel @{ Dock = 'Bottom'; Height = 46; Padding = (New-Pad 0, 8, 0, 0) }
$btnBackup  = New-Ctl Button @{ Text = '4) Back up selected'; Width = 160; Height = 30 }
$btnRestore = New-Ctl Button @{ Text = 'Restore / migrate...'; Width = 150; Height = 30 }
$btnFab     = New-Ctl Button @{ Text = "Launch Fab's AutoBackup"; Width = 190; Height = 30 }
$btnMsp     = New-Ctl Button @{ Text = 'Launch MSP360'; Width = 140; Height = 30 }
$btnLogBk   = New-Ctl Button @{ Text = 'Log a backup to report...'; Width = 180; Height = 30 }
$btnBkTicket = New-Ctl Button @{ Text = 'Send record to ticket'; Width = 170; Height = 30 }
$bkBtns.Controls.AddRange([System.Windows.Forms.Control[]]@($btnBackup, $btnRestore, $btnFab, $btnMsp, $btnLogBk, $btnBkTicket))

$bkHelp = New-Ctl Label @{ Dock = 'Top'; Height = 76; Padding = (New-Pad 2, 4, 2, 2); Text = (
    "Copy or move a customer's files in 4 steps:" + [Environment]::NewLine +
    "1) Pick the Source and click Scan profiles.    2) Tick which user(s) and what to include." + [Environment]::NewLine +
    "3) Choose a Destination folder (Browse).    4) Click '4) Back up selected'." + [Environment]::NewLine +
    "Restore / migrate = copy a backup onto this PC.   Launch Fab's AutoBackup = hand off to that tool.   Log a backup to report = record it on the ticket.") }
# Add order matters for docking: Fill first, then edges; the Destination box and button bar are pinned to the bottom so they never get cut off.
$tabBackup.Controls.Add($tlMid)
$tabBackup.Controls.Add($gbSrc)
$tabBackup.Controls.Add($gbDest)
$tabBackup.Controls.Add($bkHelp)
$tabBackup.Controls.Add($bkBtns)

function Set-SrcMode {
    $other = $rbOther.Checked
    $txtSrcRoot.Enabled = $other; $btnSrcBrowse.Enabled = $other
    if (-not $other) { $txtSrcRoot.Text = (Join-Path $env:SystemDrive 'Users') }
}
$rbThisPC.Add_CheckedChanged({ Set-SrcMode })
$rbOther.Add_CheckedChanged({ Set-SrcMode })
$btnSrcBrowse.Add_Click({
    $dlg = New-Object System.Windows.Forms.FolderBrowserDialog; $dlg.Description = 'Pick the Users folder to scan (e.g. D:\Users on a mounted old drive).'
    if ($dlg.ShowDialog($form) -eq 'OK') { $txtSrcRoot.Text = $dlg.SelectedPath }
})
$btnDestBrowse.Add_Click({
    $dlg = New-Object System.Windows.Forms.FolderBrowserDialog; $dlg.Description = 'Pick where the backup should be saved.'
    if ($dlg.ShowDialog($form) -eq 'OK') { $txtDest.Text = $dlg.SelectedPath }
})
function Show-Profiles {
    $lvProfiles.BeginUpdate(); $lvProfiles.Items.Clear()
    foreach ($p in @($Sync.Profiles)) {
        if (-not $p) { continue }
        $it = New-Object System.Windows.Forms.ListViewItem([string]$p.User)
        [void]$it.SubItems.Add(('{0:N0} MB' -f $p.DataMB)); [void]$it.SubItems.Add([string]$p.Path)
        $it.Tag = $p.Path; $it.Checked = $true
        [void]$lvProfiles.Items.Add($it)
    }
    $lvProfiles.EndUpdate()
}
$btnScanProf.Add_Click({
    $root = if ($rbThisPC.Checked) { Join-Path $env:SystemDrive 'Users' } else { $txtSrcRoot.Text.Trim() }
    if (-not $root) { Show-Msg 'Enter or browse to the folder to scan.'; return }
    Start-Background -Script $ProfileScanScript -Vars @{ Root = $root } -Status 'Scanning user profiles...' -OnComplete { Show-Profiles }
})
$btnBackup.Add_Click({
    $dest = $txtDest.Text.Trim()
    if (-not $dest) { Show-Msg 'Choose a destination folder first.'; return }
    $users = @($lvProfiles.CheckedItems | ForEach-Object { [string]$_.Tag })
    if (-not $users.Count) { Show-Msg 'Scan profiles, then tick at least one user.'; return }
    $cats = @($clbCats.CheckedItems | ForEach-Object { [string]$_ })
    if (-not $cats.Count) { Show-Msg 'Tick at least one data category.'; return }
    $srcLabel = if ($rbThisPC.Checked) { $env:COMPUTERNAME } else { 'RecoveredData' }
    $ticket = $txtTicket.Text.Trim()
    $pfx = if ($ticket) { ($ticket -replace '[^\w\-]', '') + '_' } else { '' }
    $setName = '{0}{1}_{2:yyyyMMdd-HHmm}' -f $pfx, $srcLabel, (Get-Date)
    $destSet = Join-Path $dest $setName
    $jobs = New-Object System.Collections.Generic.List[object]
    foreach ($uPath in $users) {
        $uName = Split-Path $uPath -Leaf
        foreach ($cat in $cats) {
            foreach ($rel in $BackupMap[$cat]) {
                $jobs.Add([pscustomobject]@{ Label = ('{0} / {1}' -f $uName, $cat); From = (Join-Path $uPath $rel); To = (Join-Path $destSet (Join-Path $uName $rel)) })
            }
        }
    }
    if (-not (Confirm-YesNo ("Back up {0} user(s) and {1} categor(ies) to:`r`n{2}`r`n`r`nTip: close browsers and Outlook first so their files aren't locked.`r`n`r`nContinue?" -f $users.Count, $cats.Count, $destSet))) { return }
    $script:LastBkSrc = '{0} user(s) on {1}' -f $users.Count, $srcLabel
    $script:LastBkDest = $destSet
    Start-Background -Script $CopyJobScript -Vars @{ Jobs = $jobs.ToArray() } -Status 'Backing up data...' -Total $jobs.Count -OnComplete {
        Add-BackupRecordLine $script:LastBkSrc $script:LastBkDest 'Backed up with BenchKit'
        Invoke-BackupTicketOffer
    }
})
$btnRestore.Add_Click({
    $dlg = New-Object System.Windows.Forms.FolderBrowserDialog; $dlg.Description = 'Pick the backup folder for ONE user (the folder that contains Documents, Desktop, AppData...).'
    if ($dlg.ShowDialog($form) -ne 'OK') { return }
    $setUser = $dlg.SelectedPath
    $dlg2 = New-Object System.Windows.Forms.FolderBrowserDialog; $dlg2.Description = 'Pick the destination user profile to restore into (e.g. C:\Users\Name).'; $dlg2.SelectedPath = $env:USERPROFILE
    if ($dlg2.ShowDialog($form) -ne 'OK') { return }
    $target = $dlg2.SelectedPath
    $cats = @($clbCats.CheckedItems | ForEach-Object { [string]$_ })
    if (-not $cats.Count) { Show-Msg 'Tick the categories to restore.'; return }
    $jobs = New-Object System.Collections.Generic.List[object]
    foreach ($cat in $cats) {
        foreach ($rel in $BackupMap[$cat]) {
            $jobs.Add([pscustomobject]@{ Label = ('Restore {0}' -f $cat); From = (Join-Path $setUser $rel); To = (Join-Path $target $rel) })
        }
    }
    if (-not (Confirm-YesNo ("Restore {0} categor(ies) from:`r`n{1}`r`ninto:`r`n{2}`r`n`r`nContinue?" -f $cats.Count, $setUser, $target))) { return }
    $script:LastBkSrc = $setUser; $script:LastBkDest = $target
    Start-Background -Script $CopyJobScript -Vars @{ Jobs = $jobs.ToArray() } -Status 'Restoring data...' -Total $jobs.Count -OnComplete {
        Add-BackupRecordLine $script:LastBkSrc $script:LastBkDest 'Restored with BenchKit'
        Invoke-BackupTicketOffer
    }
})
$btnFab.Add_Click({
    $p = $script:Settings.FabPath
    if (-not $p -or -not (Test-Path -LiteralPath $p)) {
        $dlg = New-Ctl OpenFileDialog @{ Filter = "Fab's AutoBackup|*.exe|All files|*.*"; Title = "Locate Fab's AutoBackup (.exe)" }
        if ($dlg.ShowDialog($form) -ne 'OK') { return }
        $p = $dlg.FileName; $script:Settings.FabPath = $p; Save-Settings; $txtFab.Text = $p
    }
    try { Start-Process -FilePath $p; Write-Ui "Launched Fab's AutoBackup. When it's done, use 'Log a backup to report' to record it on the ticket." 'OK' }
    catch { Show-Msg ("Could not launch: {0}" -f $_.Exception.Message) 'Warning' }
})
function Find-Msp360 {
    if ($script:Settings.Msp360Path -and (Test-Path -LiteralPath $script:Settings.Msp360Path)) { return $script:Settings.Msp360Path }
    $cands = @(
        "$env:ProgramFiles\MSP360\Online Backup\Online Backup.exe",
        "$env:ProgramFiles\Online Backup\Online Backup.exe",
        "${env:ProgramFiles(x86)}\MSP360\Online Backup\Online Backup.exe"
    )
    foreach ($c in $cands) { if ($c -and (Test-Path -LiteralPath $c)) { return $c } }
    foreach ($base in @($env:ProgramFiles, ${env:ProgramFiles(x86)})) {
        if (-not $base -or -not (Test-Path -LiteralPath $base)) { continue }
        $hit = Get-ChildItem -LiteralPath $base -Directory -Filter 'MSP360*' -ErrorAction SilentlyContinue |
            ForEach-Object { Get-ChildItem -LiteralPath $_.FullName -Recurse -Include 'Online Backup.exe', 'cbb.exe' -ErrorAction SilentlyContinue } |
            Select-Object -First 1
        if ($hit) { return $hit.FullName }
    }
    return $null
}
$btnMsp.Add_Click({
    $p = Find-Msp360
    if (-not $p) {
        if (-not (Confirm-YesNo "MSP360 wasn't found automatically. Locate its program file (Online Backup.exe or cbb.exe)?")) { return }
        $dlg = New-Ctl OpenFileDialog @{ Filter = 'MSP360 / Online Backup|Online Backup.exe;cbb.exe|Programs|*.exe|All files|*.*'; Title = 'Locate your MSP360 backup client' }
        if ($dlg.ShowDialog($form) -ne 'OK') { return }
        $p = $dlg.FileName
    }
    $script:Settings.Msp360Path = $p; Save-Settings; $txtMsp.Text = $p
    try { Start-Process -FilePath $p; Write-Ui "Launched MSP360. When the backup is done, use 'Send record to ticket' (or 'Log a backup to report')." 'OK' }
    catch { Show-Msg ('Could not launch MSP360: {0}' -f $_.Exception.Message) 'Warning' }
})
$btnLogBk.Add_Click({
    $dlg = New-Object System.Windows.Forms.FolderBrowserDialog; $dlg.Description = 'Pick the folder the backup was saved to (what Fab''s AutoBackup wrote).'
    if ($dlg.ShowDialog($form) -ne 'OK') { return }
    $d = $dlg.SelectedPath
    $note = [Microsoft.VisualBasic.Interaction]::InputBox('Optional note (what was saved):', 'Log backup to report', '')
    $src = if ($note.Trim()) { 'Customer data - ' + $note.Trim() } else { 'Customer data' }
    Add-BackupRecordLine $src $d "Backed up with Fab's AutoBackup"
    Show-Msg 'Recorded. It will appear in the Data backup section when you generate the report.'
})

# Post the session's backup actions onto a ticket via the upload-code pipeline.
function Resolve-TicketCreds {
    $woid = ''; $code = ''; $url = ''
    try { $woid = $tkWoid.Text.Trim() } catch { }
    try { $code = $tkCode.Text.Trim() } catch { }
    try { $url = $tkUrl.Text.Trim() } catch { }
    if ($woid -notmatch '^\d+$') { try { $woid = $txtTicket.Text.Trim() } catch { } }
    if ($woid -notmatch '^\d+$') { $woid = ([Microsoft.VisualBasic.Interaction]::InputBox('Ticket (work order) number:', 'Send to ticket', '')).Trim() }
    if ($woid -notmatch '^\d+$') { return $null }
    if ($code -notmatch '^\d{5}$') { $code = ([Microsoft.VisualBasic.Interaction]::InputBox("5-digit upload code (from the ticket's Diagnostic Reports panel):", 'Send to ticket', '')).Trim() }
    if ($code -notmatch '^\d{5}$') { return $null }
    if (-not $url) { $url = $script:Settings.TrackerUrl }
    return @{ Woid = $woid; Code = $code; Url = $url }
}
function Get-BackupRecordText {
    $recs = @($Sync.BackupRecord.ToArray())
    $sb = New-Object System.Text.StringBuilder
    [void]$sb.AppendLine('BenchKit - Data Backup Record')
    [void]$sb.AppendLine(('Generated: {0}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm')))
    [void]$sb.AppendLine(('Computer: {0}' -f $env:COMPUTERNAME))
    [void]$sb.AppendLine(('Technician: {0}' -f $script:Settings.TechName))
    [void]$sb.AppendLine('')
    if ($recs.Count) { foreach ($r in $recs) { [void]$sb.AppendLine(('{0}  {1}  ->  {2}  [{3}]' -f $r.Time, $r.Source, $r.Destination, $r.Result)) } }
    else { [void]$sb.AppendLine('(no backup actions recorded this session)') }
    return $sb.ToString()
}
function Send-BackupRecordToTicket {
    if ($Sync.Busy) { Show-Msg 'Another task is still running. Try again once it finishes.'; return }
    if (-not @($Sync.BackupRecord.ToArray()).Count) { Show-Msg 'No backup actions have been recorded yet this session.'; return }
    $creds = Resolve-TicketCreds
    if (-not $creds) { Show-Msg 'A ticket number and 5-digit upload code are needed to send the record to the ticket.'; return }
    $vars = @{ Url = $creds.Url; Woid = $creds.Woid; Code = $creds.Code; Title = ('Data backup - {0:yyyy-MM-dd HH:mm}' -f (Get-Date)); BodyOverride = (Get-BackupRecordText); PreviewOnly = $false }
    Start-Background -Script $TrackerUploadScript -Vars $vars -Status ('Sending backup record to ticket #{0}...' -f $creds.Woid)
}
function Invoke-BackupTicketOffer {
    if (Confirm-YesNo 'Backup finished. Add a record of what was done to the ticket now?') { Send-BackupRecordToTicket }
}
$btnBkTicket.Add_Click({ Send-BackupRecordToTicket })

# ---- Toolbox (download portable repair tools on demand) ------------------------------------
$tabToolbox = New-Ctl TabPage @{ Text = 'Toolbox'; Padding = (New-Pad 8) }
$tbTop = New-Ctl FlowLayoutPanel @{ Dock = 'Top'; Height = 44; WrapContents = $false }
$btnTbGet     = New-Ctl Button @{ Text = 'Download && launch'; Width = 160; Height = 30 }
$btnTbLaunch  = New-Ctl Button @{ Text = 'Launch cached'; Width = 120; Height = 30 }
$btnTbAll     = New-Ctl Button @{ Text = 'Download all (offline)'; Width = 170; Height = 30 }
$btnTbFolder  = New-Ctl Button @{ Text = 'Open folder'; Width = 110; Height = 30 }
$btnTbEdit    = New-Ctl Button @{ Text = 'Edit list'; Width = 90; Height = 30 }
$btnTbRefresh = New-Ctl Button @{ Text = 'Refresh'; Width = 90; Height = 30 }
$tbTop.Controls.AddRange([System.Windows.Forms.Control[]]@($btnTbGet, $btnTbLaunch, $btnTbAll, $btnTbFolder, $btnTbEdit, $btnTbRefresh))
$lblTb = New-Ctl Label @{ Dock = 'Bottom'; Height = 46; Text = 'Free, reputable portable tools, downloaded on demand from the vendor to your Toolbox cache (zips auto-extract). Items marked "Open page" have no stable direct link, so the vendor page opens instead. URLs change over time - use "Edit list" to fix a URL or add your own tools. Always your call whether to run a given tool on a customer PC.' }
$lvTb = New-Ctl ListView @{ View = 'Details'; Dock = 'Fill'; FullRowSelect = $true; MultiSelect = $true }
[void]$lvTb.Columns.Add('Tool', 230); [void]$lvTb.Columns.Add('Category', 170); [void]$lvTb.Columns.Add('Status', 140); [void]$lvTb.Columns.Add('Source', 140)
$tabToolbox.Controls.Add($lvTb); $tabToolbox.Controls.Add($tbTop); $tabToolbox.Controls.Add($lblTb); $lvTb.BringToFront()

function Update-ToolboxList {
    $lvTb.BeginUpdate(); $lvTb.Items.Clear(); $lvTb.Groups.Clear()
    $groups = @{}
    foreach ($t in (Get-Toolbox)) {
        if (-not $groups.ContainsKey($t.Category)) {
            $g = New-Object System.Windows.Forms.ListViewGroup($t.Category)
            [void]$lvTb.Groups.Add($g); $groups[$t.Category] = $g
        }
        $it = New-Object System.Windows.Forms.ListViewItem([string]$t.Name)
        $it.Group = $groups[$t.Category]
        if ($t.Kind -eq 'page') { $status = 'Vendor site' }
        elseif (Test-Path -LiteralPath (Join-Path $ToolboxDir $t.Name)) { $status = 'Cached'; $it.ForeColor = [System.Drawing.Color]::FromArgb(40, 160, 90) }
        else { $status = 'Not downloaded' }
        [void]$it.SubItems.Add([string]$t.Category); [void]$it.SubItems.Add($status)
        [void]$it.SubItems.Add($(if ($t.Kind -eq 'page') { 'Open page' } else { 'Direct download' }))
        $it.Tag = $t
        [void]$lvTb.Items.Add($it)
    }
    $lvTb.EndUpdate()
}
function Get-TbSelected { @($lvTb.SelectedItems | ForEach-Object { $_.Tag }) }
function Start-ToolboxItem($t) {
    if (-not $t) { return }
    if ($t.Kind -eq 'page') { try { Start-Process $t.Url } catch { }; return }
    $folder = Join-Path $ToolboxDir $t.Name
    $target = $null
    if ($t.PSObject.Properties['Exe'] -and $t.Exe) {
        $p = Join-Path $folder $t.Exe
        if (Test-Path -LiteralPath $p) { $target = $p }
        else { $f = Get-ChildItem -LiteralPath $folder -Recurse -Filter $t.Exe -ErrorAction SilentlyContinue | Select-Object -First 1; if ($f) { $target = $f.FullName } }
    } elseif ($t.File -and $t.File -notmatch '\.zip$') {
        $p = Join-Path $folder $t.File
        if (Test-Path -LiteralPath $p) { $target = $p }
    }
    if ($target) { try { Start-Process -FilePath $target -WorkingDirectory (Split-Path $target) } catch { Show-Msg ('Could not launch: {0}' -f $_.Exception.Message) 'Warning' } }
    elseif (Test-Path -LiteralPath $folder) { Start-Process explorer.exe $folder }
    else { Show-Msg ('{0} is not downloaded yet. Select it and press "Download && launch".' -f $t.Name) }
}
$btnTbGet.Add_Click({
    $sel = @(Get-TbSelected)
    if (-not $sel.Count) { Show-Msg 'Select one or more tools first.'; return }
    if ($Sync.Busy) { Show-Msg 'Another task is still running.'; return }
    $need = @($sel | Where-Object { $_.Kind -eq 'file' -and -not (Test-Path -LiteralPath (Join-Path $ToolboxDir $_.Name)) })
    if ($need.Count) {
        Start-Background -Script $ToolboxDownloadScript -Vars @{ Items = $need; Dir = $ToolboxDir } -Status 'Downloading tools...' -OnComplete {
            Update-ToolboxList
            foreach ($t in $script:TbPending) { Start-ToolboxItem $t }
            $script:TbPending = @()
        }
        $script:TbPending = $sel
    } else {
        foreach ($t in $sel) { Start-ToolboxItem $t }
    }
})
$btnTbLaunch.Add_Click({
    $sel = @(Get-TbSelected)
    if (-not $sel.Count) { Show-Msg 'Select a cached tool first.'; return }
    foreach ($t in $sel) { Start-ToolboxItem $t }
})
$btnTbAll.Add_Click({
    if ($Sync.Busy) { Show-Msg 'Another task is still running.'; return }
    $files = @(Get-Toolbox | Where-Object { $_.Kind -eq 'file' })
    if (-not (Confirm-YesNo ('Download all {0} directly-downloadable tools to the Toolbox cache for offline use? (Items that only have a vendor page are skipped.)' -f $files.Count))) { return }
    Start-Background -Script $ToolboxDownloadScript -Vars @{ Items = $files; Dir = $ToolboxDir } -Status 'Downloading all tools...' -OnComplete { Update-ToolboxList }
})
$btnTbFolder.Add_Click({ Initialize-DataDirs; Start-Process explorer.exe $ToolboxDir })
$btnTbEdit.Add_Click({
    if (-not (Test-Path -LiteralPath $ToolboxFile)) {
        try { Get-Toolbox | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath $ToolboxFile -Encoding UTF8 } catch { }
    }
    Start-Process notepad.exe $ToolboxFile
    Show-Msg 'Edit the list in Notepad, save it, then press Refresh. Each entry needs Name, Category, Kind ("file" or "page") and Url; "file" entries also need File (and optionally Exe for a zip).'
})
$btnTbRefresh.Add_Click({ Update-ToolboxList })
Update-ToolboxList

# ---- Repair Tracker (submit a report to a PCRT ticket via the upload-code pipeline) --------
$tabTracker = New-Ctl TabPage @{ Text = 'Repair Tracker'; Padding = (New-Pad 12) }
$tkInfo = New-Ctl Label @{ Dock = 'Top'; Height = 72; Text = ("Send a plain-text diagnostic report straight onto a work order in your repair tracker." + [Environment]::NewLine + "In the ticket, open 'Diagnostic Reports - Review / Upload Code' to get the 5-digit upload code, enter it below with the ticket number, and press Upload. You then review and accept the report inside the ticket. No passwords, product keys or recovery keys are ever included.") }
$tkGrid = New-Ctl TableLayoutPanel @{ Dock = 'Top'; ColumnCount = 2; Height = 210; AutoSize = $false }
[void]$tkGrid.ColumnStyles.Add((New-Object System.Windows.Forms.ColumnStyle([System.Windows.Forms.SizeType]::Absolute, 150)))
[void]$tkGrid.ColumnStyles.Add((New-Object System.Windows.Forms.ColumnStyle([System.Windows.Forms.SizeType]::Percent, 100)))
$tkUrl    = New-Ctl TextBox @{ Width = 520; Text = [string]$Settings.TrackerUrl }
$tkWoid   = New-Ctl TextBox @{ Width = 160 }
$tkCode   = New-Ctl TextBox @{ Width = 160; MaxLength = 5 }
$tkTitle  = New-Ctl TextBox @{ Width = 420; Text = ('BenchKit scan - {0:yyyy-MM-dd}' -f (Get-Date)) }
$tkFind   = New-Ctl CheckBox @{ Text = 'Diagnostics findings'; AutoSize = $true; Checked = $true }
$tkWork   = New-Ctl CheckBox @{ Text = 'Work performed'; AutoSize = $true; Checked = $true }
$tkScan   = New-Ctl CheckBox @{ Text = 'Security / remote-access scan'; AutoSize = $true; Checked = $true }
$tkChecks = New-Ctl FlowLayoutPanel @{ AutoSize = $true }
$tkChecks.Controls.AddRange([System.Windows.Forms.Control[]]@($tkFind, $tkWork, $tkScan))
$tkRows = @(
    @('Tracker URL', $tkUrl), @('Ticket number', $tkWoid), @('Upload code (5 digits)', $tkCode), @('Report title', $tkTitle), @('Include', $tkChecks)
)
$r = 0
foreach ($rr in $tkRows) {
    $tkGrid.Controls.Add((New-Ctl Label @{ Text = $rr[0]; AutoSize = $true; Padding = (New-Pad 0, 6, 0, 0) }), 0, $r)
    $tkGrid.Controls.Add($rr[1], 1, $r); $r++
}
$tkBtns = New-Ctl FlowLayoutPanel @{ Dock = 'Top'; Height = 46; Padding = (New-Pad 150, 6, 0, 0) }
$btnTkPreview = New-Ctl Button @{ Text = 'Preview report'; Width = 140; Height = 30 }
$btnTkUpload  = New-Ctl Button @{ Text = 'Upload to ticket'; Width = 150; Height = 30 }
$btnTkSaveUrl = New-Ctl Button @{ Text = 'Save URL'; Width = 100; Height = 30 }
$tkBtns.Controls.AddRange([System.Windows.Forms.Control[]]@($btnTkPreview, $btnTkUpload, $btnTkSaveUrl))
# Saved-reports picker: tick files from the Reports folder and upload them to the ticket above.
$gbSaved = New-Ctl GroupBox @{ Text = 'Saved reports - tick to upload to the ticket above (text goes to the inbox; HTML attaches to the ticket)'; Dock = 'Fill'; Padding = (New-Pad 8) }
# Top bar: filter + one-click selection so techs don't have to tick rows one at a time in a small window.
$savedTop = New-Ctl FlowLayoutPanel @{ Dock = 'Top'; Height = 36; Padding = (New-Pad 0, 2, 0, 4); WrapContents = $false; AutoSize = $false }
$lblFilter = New-Ctl Label @{ Text = 'Show:'; AutoSize = $true; Padding = (New-Pad 0, 8, 4, 0) }
$cmbFilter = New-Ctl ComboBox @{ Width = 130; DropDownStyle = 'DropDownList' }
[void]$cmbFilter.Items.AddRange([object[]]@('All files', 'HTML only', 'Text only'))
$cmbFilter.SelectedIndex = 0
$btnSelHtml = New-Ctl Button @{ Text = 'Tick all HTML'; Width = 120; Height = 26; Margin = (New-Pad 10, 2, 2, 2) }
$btnSelAll  = New-Ctl Button @{ Text = 'Tick all'; Width = 90; Height = 26; Margin = (New-Pad 2) }
$btnSelNone = New-Ctl Button @{ Text = 'Untick all'; Width = 90; Height = 26; Margin = (New-Pad 2) }
$savedTop.Controls.AddRange([System.Windows.Forms.Control[]]@($lblFilter, $cmbFilter, $btnSelHtml, $btnSelAll, $btnSelNone))
# The list itself: multi-column with checkboxes, far easier to read than a single-line box.
$lvSaved = New-Ctl ListView @{ Dock = 'Fill'; CheckBoxes = $true; View = 'Details'; FullRowSelect = $true; GridLines = $true; HideSelection = $false; MultiSelect = $true }
[void]$lvSaved.Columns.Add('Report', 320)
[void]$lvSaved.Columns.Add('Type', 70)
[void]$lvSaved.Columns.Add('Modified', 130)
[void]$lvSaved.Columns.Add('Size', 70)
$savedBtns = New-Ctl FlowLayoutPanel @{ Dock = 'Bottom'; Height = 44; Padding = (New-Pad 0, 6, 0, 0) }
$btnSavedText    = New-Ctl Button @{ Text = 'Upload ticked as text'; Width = 170; Height = 30 }
$btnSavedHtml    = New-Ctl Button @{ Text = 'Attach ticked as HTML'; Width = 170; Height = 30 }
$btnSavedRefresh = New-Ctl Button @{ Text = 'Refresh list'; Width = 100; Height = 30 }
$btnSavedOpen    = New-Ctl Button @{ Text = 'Open folder'; Width = 110; Height = 30 }
$savedBtns.Controls.AddRange([System.Windows.Forms.Control[]]@($btnSavedText, $btnSavedHtml, $btnSavedRefresh, $btnSavedOpen))
$gbSaved.Controls.Add($savedBtns); $gbSaved.Controls.Add($lvSaved); $gbSaved.Controls.Add($savedTop)
# Resizable split: the ticket form on top, the reports list below, with a draggable divider so the
# list can be made as tall as needed even when the whole window is small.
# Create with default min sizes; setting min sizes now (while the control is still at its tiny
# default height) would make the splitter position invalid and throw. We size it once below, after
# it has a real height, in an order that always keeps SplitterDistance within the allowed range.
$tkSplit = New-Ctl SplitContainer @{ Dock = 'Fill'; SplitterWidth = 6 }
$tkSplit.Orientation = 'Horizontal'
$tkSplit.Panel1.AutoScroll = $true
$tkGrid.Dock = 'Top'; $tkBtns.Dock = 'Top'
$tkSplit.Panel1.Controls.Add($tkBtns); $tkSplit.Panel1.Controls.Add($tkGrid)
$tkSplit.Panel2.Controls.Add($gbSaved)
$tabTracker.Controls.Add($tkSplit); $tabTracker.Controls.Add($tkInfo)
# One-time sizing: runs the first time the split has a usable height (at form show, or when the
# tab is first opened), then stops so it never fights the tech's manual dragging.
$script:TkSplitInit = $false
$sizeTkSplit = {
    if ($script:TkSplitInit) { return }
    try {
        $h = $tkSplit.Height
        if ($h -lt 200) { return }
        $sw = $tkSplit.SplitterWidth
        # Drop mins to 0 first so the next SplitterDistance set is always valid, then clamp & raise.
        $tkSplit.Panel1MinSize = 0; $tkSplit.Panel2MinSize = 0
        $d = [int]($h * 0.45)
        if ($d -lt 60) { $d = 60 }
        if ($d -gt ($h - 60 - $sw)) { $d = $h - 60 - $sw }
        $tkSplit.SplitterDistance = $d
        $p1 = [Math]::Min(80, $d); if ($p1 -lt 0) { $p1 = 0 }
        $p2 = [Math]::Min(150, $h - $d - $sw); if ($p2 -lt 0) { $p2 = 0 }
        $tkSplit.Panel1MinSize = $p1; $tkSplit.Panel2MinSize = $p2
        $script:TkSplitInit = $true
    } catch { }
}
$tkSplit.Add_SizeChanged($sizeTkSplit)
$form.Add_Shown($sizeTkSplit)

function Invoke-TrackerUpload([bool]$PreviewOnly) {
    if ($Sync.Busy) { Show-Msg 'Another task is still running.'; return }
    $url = $tkUrl.Text.Trim()
    $woid = $tkWoid.Text.Trim()
    $code = $tkCode.Text.Trim()
    $title = ($tkTitle.Text -replace '[\r\n\t]+', ' ').Trim()
    if ($title.Length -gt 160) { $title = $title.Substring(0, 160) }
    if (-not $PreviewOnly) {
        if (-not $url) { Show-Msg 'Enter the Tracker URL (your report-upload.php address).'; return }
        if ($woid -notmatch '^\d+$') { Show-Msg 'Enter the numeric ticket (work order) number.'; return }
        if ($code -notmatch '^\d{5}$') { Show-Msg 'Enter the 5-digit upload code from the ticket''s Diagnostic Reports panel.'; return }
        if (-not $title) { Show-Msg 'Enter a report title.'; return }
    }
    $vars = @{
        Url = $url; Woid = $woid; Code = $code; Title = $title; Tech = $script:Settings.TechName
        Findings = $Sync.Findings; Work = @($Sync.WorkDone.ToArray()); RemoteScan = $Sync.RemoteScan
        IncludeFindings = $tkFind.Checked; IncludeWork = $tkWork.Checked; IncludeScan = $tkScan.Checked
        PreviewOnly = $PreviewOnly
    }
    $status = if ($PreviewOnly) { 'Building report preview...' } else { 'Uploading report to ticket...' }
    Start-Background -Script $TrackerUploadScript -Vars $vars -Status $status
}
$btnTkPreview.Add_Click({ Invoke-TrackerUpload $true })
$btnTkUpload.Add_Click({ Invoke-TrackerUpload $false })
$btnTkSaveUrl.Add_Click({
    $script:Settings.TrackerUrl = $tkUrl.Text.Trim(); Save-Settings; Write-Ui 'Tracker URL saved.' 'OK'
})

function Update-SavedReports {
    $mode = [string]$cmbFilter.SelectedItem
    $lvSaved.BeginUpdate()
    $lvSaved.Items.Clear()
    if (Test-Path -LiteralPath $ReportDir) {
        foreach ($fi in (Get-ChildItem -LiteralPath $ReportDir -File -ErrorAction SilentlyContinue | Where-Object { $_.Extension -match '^\.(html?|txt|pdf)$' } | Sort-Object LastWriteTime -Descending)) {
            $ext = $fi.Extension.ToLower()
            $isHtml = ($ext -eq '.html' -or $ext -eq '.htm')
            $isText = ($ext -eq '.txt')
            if ($mode -eq 'HTML only' -and -not $isHtml) { continue }
            if ($mode -eq 'Text only' -and -not $isText) { continue }
            $type = if ($isHtml) { 'HTML' } elseif ($isText) { 'Text' } else { $ext.TrimStart('.').ToUpper() }
            $it = New-Object System.Windows.Forms.ListViewItem($fi.Name)
            [void]$it.SubItems.Add($type)
            [void]$it.SubItems.Add(('{0:yyyy-MM-dd HH:mm}' -f $fi.LastWriteTime))
            [void]$it.SubItems.Add(('{0:N0} KB' -f ($fi.Length / 1KB)))
            $it.Tag = $fi.FullName
            [void]$lvSaved.Items.Add($it)
        }
    }
    $lvSaved.EndUpdate()
}
function Get-CheckedSavedFiles { $out = @(); foreach ($it in $lvSaved.CheckedItems) { $out += [string]$it.Tag }; return @($out) }
$cmbFilter.Add_SelectedIndexChanged({ Update-SavedReports })
$btnSelHtml.Add_Click({ foreach ($it in $lvSaved.Items) { $it.Checked = ([string]$it.Tag -match '\.html?$') } })
$btnSelAll.Add_Click({ foreach ($it in $lvSaved.Items) { $it.Checked = $true } })
$btnSelNone.Add_Click({ foreach ($it in $lvSaved.Items) { $it.Checked = $false } })
$lvSaved.Add_DoubleClick({ $it = $lvSaved.FocusedItem; if ($it) { try { Start-Process -FilePath ([string]$it.Tag) } catch { } } })
$lvSaved.Add_Resize({ $w = $lvSaved.ClientSize.Width - 70 - 130 - 70 - 6; if ($w -gt 160) { $lvSaved.Columns[0].Width = $w } })
$btnSavedRefresh.Add_Click({ Update-SavedReports })
$btnSavedOpen.Add_Click({ Initialize-DataDirs; Start-Process explorer.exe $ReportDir })
$btnSavedText.Add_Click({
    if ($Sync.Busy) { Show-Msg 'Another task is still running.'; return }
    $sel = Get-CheckedSavedFiles
    if (-not $sel.Count) { Show-Msg 'Tick at least one saved report to upload.'; return }
    $url = $tkUrl.Text.Trim(); $woid = $tkWoid.Text.Trim(); $code = $tkCode.Text.Trim()
    if (-not $url) { Show-Msg 'Enter the Tracker URL above.'; return }
    if ($woid -notmatch '^\d+$') { Show-Msg 'Enter the ticket number above.'; return }
    if ($code -notmatch '^\d{5}$') { Show-Msg 'Enter the 5-digit upload code above.'; return }
    Start-Background -Script $TrackerUploadFilesScript -Vars @{ Url = $url; Woid = $woid; Code = $code; Files = $sel } -Status 'Uploading reports as text...'
})
$btnSavedHtml.Add_Click({
    if ($Sync.Busy) { Show-Msg 'Another task is still running.'; return }
    $sel = @(Get-CheckedSavedFiles | Where-Object { $_ -match '\.html?$' })
    if (-not $sel.Count) { Show-Msg 'Tick at least one HTML report - only .html files can be attached as HTML.'; return }
    $woid = $tkWoid.Text.Trim()
    if ($woid -notmatch '^\d+$') { Show-Msg 'Enter the ticket number above.'; return }
    $hash = $script:Settings.StoreHash; $aurl = $script:Settings.AttachUrl
    if (-not $hash) { Show-Msg 'Set your Store hash in Settings (Integrations) first - HTML attachments need it.'; Show-Tab $tabSet; return }
    if (-not $aurl) { Show-Msg 'Set the HTML attach URL in Settings.'; return }
    Start-Background -Script $AttachFilesScript -Vars @{ Url = $aurl; Hash = $hash; Woid = $woid; Files = $sel } -Status 'Attaching HTML reports to the ticket...'
})
Update-SavedReports

# ---- Devices (scan the local network: printers, NAS, routers, cameras, PCs) -----------------
$tabDevices = New-Ctl TabPage @{ Text = 'Devices'; Padding = (New-Pad 12) }
$devInfo = New-Ctl Label @{ Dock = 'Top'; Height = 44; Text = ("Scan the local network to find printers, NAS boxes, routers, cameras and PCs. Double-click a device (or use Open web admin) to open its web page in a browser." + [Environment]::NewLine + "Only the local subnet is scanned; it reads the network and changes nothing.") }
$devTop = New-Ctl FlowLayoutPanel @{ Dock = 'Top'; Height = 40; WrapContents = $false; AutoSize = $false }
$btnDevScan = New-Ctl Button @{ Text = 'Scan network'; Width = 140; Height = 30; Margin = (New-Pad 0, 2, 8, 2) }
$btnDevOpen = New-Ctl Button @{ Text = 'Open web admin'; Width = 150; Height = 30; Margin = (New-Pad 2) }
$btnDevReport = New-Ctl Button @{ Text = 'Build device report'; Width = 170; Height = 30; Margin = (New-Pad 2) }
$devTop.Controls.AddRange([System.Windows.Forms.Control[]]@($btnDevScan, $btnDevOpen, $btnDevReport))
$devNote = New-Ctl Label @{ Dock = 'Bottom'; Height = 40; Text = ''; Padding = (New-Pad 0, 6, 0, 0) }
$lvDev = New-Ctl ListView @{ Dock = 'Fill'; View = 'Details'; FullRowSelect = $true; GridLines = $true; HideSelection = $false; MultiSelect = $false }
[void]$lvDev.Columns.Add('IP address', 130); [void]$lvDev.Columns.Add('Name', 180); [void]$lvDev.Columns.Add('Type', 120); [void]$lvDev.Columns.Add('Vendor', 140); [void]$lvDev.Columns.Add('Open ports', 190); [void]$lvDev.Columns.Add('Web admin', 170)
$tabDevices.Controls.Add($lvDev); $tabDevices.Controls.Add($devNote); $tabDevices.Controls.Add($devTop); $tabDevices.Controls.Add($devInfo)
$lvDev.BringToFront()

$NetScanScript = @'
# Small OUI (MAC prefix) -> vendor map for common device makers. Most classification is by port.
$oui = @{
    '00-00-74' = 'Ricoh'; '00-1b-a9' = 'Brother'; '00-80-77' = 'Brother'; '00-00-85' = 'Canon'; '00-1e-8f' = 'Canon';
    '00-00-48' = 'Epson'; '00-26-ab' = 'Epson'; '00-01-e3' = 'Siemens'; '00-60-b0' = 'HP'; '00-1f-29' = 'HP'; '3c-d9-2b' = 'HP'; '98-4b-e1' = 'HP'; '00-17-a4' = 'HP';
    '00-11-32' = 'Synology'; '00-1b-a0' = 'Synology'; '00-08-9b' = 'QNAP'; '24-5e-be' = 'QNAP'; '00-14-ee' = 'Western Digital'; '00-90-a9' = 'Western Digital';
    '44-d9-e7' = 'Ubiquiti'; '00-15-6d' = 'Ubiquiti'; '24-a4-3c' = 'Ubiquiti'; '00-14-6c' = 'Netgear'; '00-1e-2a' = 'Netgear'; '50-c7-bf' = 'TP-Link'; '00-1d-0f' = 'TP-Link';
    '00-00-0c' = 'Cisco'; '00-1a-a2' = 'Cisco'; 'b8-27-eb' = 'Raspberry Pi'; 'dc-a6-32' = 'Raspberry Pi'; '00-14-22' = 'Dell'; '00-1a-a0' = 'Dell';
    '00-1c-c0' = 'Intel'; '00-04-f2' = 'Polycom'; 'c0-56-27' = 'Belkin'; '00-0c-29' = 'VMware'; '00-50-56' = 'VMware';
    '00-40-8c' = 'Axis (camera)'; 'ac-cc-8e' = 'Axis (camera)'; '00-12-12' = 'Hikvision'; 'c0-56-e3' = 'Hikvision'; '00-23-63' = 'Dahua'; '3c-ef-8c' = 'Dahua';
    '88-71-e5' = 'Amazon'; 'fc-65-de' = 'Amazon'; 'd0-03-4b' = 'Apple'; '00-25-00' = 'Apple'; 'b8-e8-56' = 'Apple'; '00-1d-ba' = 'Sony'; '00-24-e4' = 'Withings'
}
function Oui-Vendor($mac) { if (-not $mac) { return '' }; $p = ($mac -replace ':', '-').ToLower().Substring(0, 8); if ($oui.ContainsKey($p)) { return $oui[$p] } return '' }
function Test-Port($ip, $port, $ms) {
    $c = $null
    try { $c = New-Object System.Net.Sockets.TcpClient; $iar = $c.BeginConnect($ip, $port, $null, $null); $ok = $iar.AsyncWaitHandle.WaitOne($ms); if ($ok -and $c.Connected) { $c.EndConnect($iar); return $true }; return $false }
    catch { return $false } finally { if ($c) { try { $c.Close() } catch { } } }
}
function Get-RevName($ip) { try { $t = [System.Net.Dns]::GetHostEntryAsync($ip); if ($t.Wait(500)) { return ($t.Result.HostName -split '\.')[0] } } catch { } return '' }

# Find the active IPv4 subnet.
$myip = ''; $gw = ''
try {
    $cfg = Get-NetIPConfiguration -ErrorAction Stop | Where-Object { $_.IPv4DefaultGateway -and $_.NetAdapter.Status -eq 'Up' } | Select-Object -First 1
    if ($cfg) { $myip = $cfg.IPv4Address.IPAddress; $gw = $cfg.IPv4DefaultGateway.NextHop }
} catch { }
if (-not $myip) { try { $myip = (Get-NetIPAddress -AddressFamily IPv4 -ErrorAction Stop | Where-Object { $_.IPAddress -notmatch '^(127\.|169\.254\.)' } | Select-Object -First 1).IPAddress } catch { } }
if (-not $myip) { Write-Log 'Could not determine the local network address. Is this PC connected to a network?' 'ERROR'; $Sync.NetDevices = @(); return }
$base = ($myip -split '\.')[0..2] -join '.'
Write-Log ('Scanning {0}.1-254 (this PC is {1})...' -f $base, $myip) 'STEP'

# Ping sweep (concurrent) to find live hosts and populate the ARP cache.
$pending = New-Object System.Collections.ArrayList
for ($i = 1; $i -le 254; $i++) {
    $ip = "$base.$i"
    $p = New-Object System.Net.NetworkInformation.Ping
    [void]$pending.Add([pscustomobject]@{ Ip = $ip; Task = $p.SendPingAsync($ip, 600); Ping = $p })
}
$live = New-Object System.Collections.ArrayList
foreach ($e in $pending) { try { if ($e.Task.Result.Status -eq 'Success') { [void]$live.Add($e.Ip) } } catch { } finally { try { $e.Ping.Dispose() } catch { } } }
Write-Log ('{0} device(s) responded. Identifying them...' -f $live.Count) 'OK'

$arp = (arp -a) 2>&1 | Out-String
$ports = @{ 'Web' = 80; 'HTTPS' = 443; 'Alt-web' = 8080; 'Print(9100)' = 9100; 'LPD(515)' = 515; 'IPP(631)' = 631; 'SMB(445)' = 445; 'NetBIOS(139)' = 139; 'SSH(22)' = 22; 'Synology(5000)' = 5000; 'AFP(548)' = 548; 'NFS(2049)' = 2049; 'RTSP(554)' = 554; 'RDP(3389)' = 3389 }
$devices = New-Object System.Collections.ArrayList
$n = $live.Count; $idx = 0
foreach ($ip in $live) {
    $idx++
    Write-Prog ('{0}% - checking {1} ({2}/{3})' -f [int]($idx / [math]::Max($n, 1) * 100), $ip, $idx, $n)
    $mac = ''; $mm = [regex]::Match($arp, ([regex]::Escape($ip) + '\s+([0-9A-Fa-f]{2}(?:-[0-9A-Fa-f]{2}){5})')); if ($mm.Success) { $mac = $mm.Groups[1].Value.ToLower() }
    $vendor = Oui-Vendor $mac
    $open = @(); foreach ($k in $ports.Keys) { if (Test-Port $ip $ports[$k] 250) { $open += $k } }
    $name = Get-RevName $ip
    # Classify.
    $type = 'Unknown'
    $hasPrint = ($open -match 'Print\(9100\)|LPD|IPP').Count -gt 0
    $hasNas = ($open -contains 'Synology(5000)') -or ($open -contains 'AFP(548)') -or ($open -contains 'NFS(2049)')
    $hasSmb = ($open -contains 'SMB(445)') -or ($open -contains 'NetBIOS(139)')
    $hasCam = ($open -contains 'RTSP(554)')
    $hasRdp = ($open -contains 'RDP(3389)')
    if ($ip -eq $gw) { $type = 'Router / gateway' }
    elseif ($hasPrint -or $vendor -match 'Brother|Canon|Epson|HP|Ricoh') { $type = 'Printer' }
    elseif ($hasNas -or $vendor -match 'Synology|QNAP|Western Digital') { $type = 'NAS / storage' }
    elseif ($hasCam -or $vendor -match 'Hikvision|Dahua|Axis') { $type = 'Camera' }
    elseif ($hasRdp -or $vendor -match 'VMware') { $type = 'PC' }
    elseif ($hasSmb) { $type = 'PC / file share' }
    elseif ($vendor -match 'Ubiquiti|Netgear|TP-Link|Cisco') { $type = 'Network gear' }
    # Web admin URL.
    $web = ''
    if ($open -contains 'Web') { $web = "http://$ip" }
    elseif ($open -contains 'HTTPS') { $web = "https://$ip" }
    elseif ($open -contains 'Synology(5000)') { $web = "http://${ip}:5000" }
    elseif ($open -contains 'Alt-web') { $web = "http://${ip}:8080" }
    [void]$devices.Add([pscustomobject]@{ Ip = $ip; Name = $name; Type = $type; Vendor = $vendor; Ports = ($open -join ', '); Web = $web; IsGw = ($ip -eq $gw) })
}
# Sort by numeric last octet.
$Sync.NetDevices = @($devices | Sort-Object { [int](($_.Ip -split '\.')[3]) })
Write-Log ('Network scan complete - {0} device(s) found on {1}.0/24.' -f @($devices).Count, $base) 'DONE'
'@
function Show-NetDevices {
    $lvDev.BeginUpdate(); $lvDev.Items.Clear()
    foreach ($d in @($Sync.NetDevices)) {
        $nm = [string]$d.Name; if ($d.IsGw -and -not $nm) { $nm = '(this network''s router)' }
        $it = New-Object System.Windows.Forms.ListViewItem([string]$d.Ip)
        [void]$it.SubItems.Add($nm); [void]$it.SubItems.Add([string]$d.Type); [void]$it.SubItems.Add([string]$d.Vendor); [void]$it.SubItems.Add([string]$d.Ports); [void]$it.SubItems.Add([string]$d.Web)
        $it.Tag = [string]$d.Web
        if ($d.Web) { $it.ForeColor = (RGB 45 108 223) }
        [void]$lvDev.Items.Add($it)
    }
    $lvDev.EndUpdate()
    $devNote.Text = ('{0} device(s). Blue rows have a web page - double-click or use Open web admin to open it.' -f @($Sync.NetDevices).Count)
}
function Open-DevWeb { if ($lvDev.SelectedItems.Count -and $lvDev.SelectedItems[0].Tag) { try { Start-Process ([string]$lvDev.SelectedItems[0].Tag) } catch { } } else { Show-Msg 'Pick a device that has a web admin address.' } }
$btnDevScan.Add_Click({ if ($Sync.Busy) { Show-Msg 'Another task is still running.'; return }; Start-Background -Script $NetScanScript -Status 'Scanning the local network...' -OnComplete { Show-NetDevices } })
$btnDevOpen.Add_Click({ Open-DevWeb })
$lvDev.Add_DoubleClick({ Open-DevWeb })
function Build-NetReport {
    if (-not @($Sync.NetDevices).Count) { Show-Msg 'Run a network scan first.'; return }
    Initialize-DataDirs
    function E($x) { [System.Net.WebUtility]::HtmlEncode([string]$x) }
    function WL2($u) { $u = ([string]$u).Trim(); if (-not $u) { return '' }; if ($u -notmatch '^(?i)https?://') { $u = 'https://' + $u }; $d = ($u -replace '^(?i)https?://', '') -replace '/$', ''; return ('<a href="{0}">{1}</a>' -f (E $u), (E $d)) }
    $company = if ($script:Settings.CompanyName) { $script:Settings.CompanyName } else { 'Service Report' }
    $web = [string]$script:Settings.CompanyWebsite; $phone = [string]$script:Settings.CompanyPhone
    $tech = $txtTech.Text.Trim(); $cust = $txtCustomer.Text.Trim(); $ticket = $txtTicket.Text.Trim()
    $logo = Get-LogoDataUri
    $rowsH = ''
    foreach ($d in @($Sync.NetDevices)) {
        $nm = [string]$d.Name; if ($d.IsGw -and -not $nm) { $nm = '(router)' }
        $rowsH += ('<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td></tr>' -f (E $d.Ip), (E $nm), (E $d.Type), (E $d.Vendor), $(if ($d.Web) { WL2 $d.Web } else { '' }))
    }
    $meta = ''
    if ($cust) { $meta += ('<tr><th>Customer</th><td>{0}</td></tr>' -f (E $cust)) }
    if ($ticket) { $meta += ('<tr><th>Ticket / job #</th><td>{0}</td></tr>' -f (E $ticket)) }
    $meta += ('<tr><th>Scanned from</th><td>{0}</td></tr>' -f (E $env:COMPUTERNAME))
    $meta += ('<tr><th>Date</th><td>{0}</td></tr>' -f (Get-Date -Format 'yyyy-MM-dd HH:mm'))
    if ($tech) { $meta += ('<tr><th>Technician</th><td>{0}</td></tr>' -f (E $tech)) }
    $foot = (@((E $company), (WL2 $web), (E $phone)) | Where-Object { $_ }) -join ' - '
    $css = @"
body{font-family:'Segoe UI',Arial,sans-serif;margin:0;background:#f4f5f7;color:#1f2328}
header{background:#1f3a5f;color:#fff;padding:22px 32px}header h1{margin:0;font-size:24px}header p{margin:4px 0 0;opacity:.88}
header a{color:#cfe3ff} footer a{color:#2d6cdf} a{color:#2d6cdf}
main{max-width:900px;margin:0 auto;padding:16px}
section{background:#fff;border-radius:8px;padding:14px 18px;margin:14px 0;box-shadow:0 1px 3px rgba(0,0,0,.08)}
h2{font-size:17px;margin:0 0 10px;color:#1f3a5f}
table{border-collapse:collapse;width:100%;font-size:13px}th,td{text-align:left;padding:7px 9px;border-bottom:1px solid #e5e7eb}th{background:#f0f3f7}table.kv th{width:200px}
footer{text-align:center;color:#6b7280;font-size:12px;padding:20px}
@media print{body{background:#fff}section{box-shadow:none;border:1px solid #ddd}}
"@
    $html = @"
<!DOCTYPE html><html><head><meta charset="utf-8"><title>Devices on your network - $(E $env:COMPUTERNAME)</title><style>$css</style></head>
<body><header>$(if ($logo) { "<img src='$logo' alt='' style='max-height:50px;margin-bottom:8px;display:block'>" })<h1>$(E $company) - Devices on your network</h1>$(if ($tech) { "<p>Prepared by $(E $tech) on $(Get-Date -Format 'yyyy-MM-dd HH:mm')</p>" })</header>
<main><section><table class="kv">$meta</table></section>
<section><h2>Devices found ($(@($Sync.NetDevices).Count))</h2><table><tr><th>IP address</th><th>Name</th><th>Type</th><th>Vendor</th><th>Web admin</th></tr>$rowsH</table></section></main><footer>$foot</footer></body></html>
"@
    $tag = if ($ticket) { ($ticket -replace '[^\w\-]', '') + '_' } else { '' }
    $path = Join-Path $ReportDir ('devices_{0}{1}_{2:yyyyMMdd-HHmm}.html' -f $tag, $env:COMPUTERNAME, (Get-Date))
    Set-Content -LiteralPath $path -Value $html -Encoding UTF8
    Write-Ui ('Device report saved: {0}' -f $path) 'DONE'
    Start-Process $path
}
$btnDevReport.Add_Click({ Build-NetReport })

# ---- Scam Check (guided scan + report for a suspected tech-support scam / remote takeover) ---
$tabScam = New-Ctl TabPage @{ Text = 'Scam Check'; Padding = (New-Pad 12) }
$scamInfo = New-Ctl Label @{ Dock = 'Top'; Height = 44; Text = ("Read-only checkup for a customer who thinks they were scammed (fake 'tech support', remote takeover). It looks for remote-control tools, recent installs, new admin accounts, hosts/proxy/DNS changes and more - it changes nothing." + [Environment]::NewLine + "Review the findings with the customer, then build a report they can keep or take to their bank.") }
$scamTop = New-Ctl FlowLayoutPanel @{ Dock = 'Top'; Height = 40; WrapContents = $false; AutoSize = $false }
$btnScamScan = New-Ctl Button @{ Text = 'Run scam check'; Width = 150; Height = 30; Margin = (New-Pad 0, 2, 8, 2) }
$btnScamReport = New-Ctl Button @{ Text = 'Build report'; Width = 130; Height = 30; Margin = (New-Pad 2) }
$scamTop.Controls.AddRange([System.Windows.Forms.Control[]]@($btnScamScan, $btnScamReport))
$scamNote = New-Ctl Label @{ Dock = 'Bottom'; Height = 46; Text = ''; Padding = (New-Pad 0, 6, 0, 0) }
$lvScam = New-Ctl ListView @{ Dock = 'Fill'; View = 'Details'; FullRowSelect = $true; GridLines = $true; HideSelection = $false }
[void]$lvScam.Columns.Add('Level', 90); [void]$lvScam.Columns.Add('Area', 180); [void]$lvScam.Columns.Add('What we found', 560); [void]$lvScam.Columns.Add('When found', 120)
$tabScam.Controls.Add($lvScam); $tabScam.Controls.Add($scamNote); $tabScam.Controls.Add($scamTop); $tabScam.Controls.Add($scamInfo)
$lvScam.BringToFront()

$ScamScanScript = @'
$rows = New-Object System.Collections.ArrayList
function Add-Scam($Sev, $Area, $Detail) { [void]$rows.Add([pscustomobject]@{ Sev = $Sev; Area = $Area; Detail = $Detail; When = (Get-Date).ToString('yyyy-MM-dd HH:mm') }) }
# Read a registry key's last-write time (= when a program's uninstall entry was written, i.e. its
# install/update moment) so recent installs can carry a real time of day, not just a date.
if (-not ('BK.Reg' -as [type])) {
    try {
        Add-Type -Namespace BK -Name Reg -MemberDefinition @"
[System.Runtime.InteropServices.DllImport("advapi32.dll")]
public static extern int RegQueryInfoKey(Microsoft.Win32.SafeHandles.SafeRegistryHandle hKey, System.IntPtr lpClass, System.IntPtr lpcchClass, System.IntPtr lpReserved, System.IntPtr lpcSubKeys, System.IntPtr lpcbMaxSubKeyLen, System.IntPtr lpcbMaxClassLen, System.IntPtr lpcValues, System.IntPtr lpcbMaxValueNameLen, System.IntPtr lpcbMaxValueLen, System.IntPtr lpcbSecurityDescriptor, out long lpftLastWriteTime);
"@ -ErrorAction Stop
    } catch { }
}
function Get-KeyWriteTime($key) {
    try {
        $ft = [long]0
        if ([BK.Reg]::RegQueryInfoKey($key.Handle, [IntPtr]::Zero, [IntPtr]::Zero, [IntPtr]::Zero, [IntPtr]::Zero, [IntPtr]::Zero, [IntPtr]::Zero, [IntPtr]::Zero, [IntPtr]::Zero, [IntPtr]::Zero, [IntPtr]::Zero, [ref]$ft) -eq 0) { return [DateTime]::FromFileTime($ft) }
    } catch { }
    return $null
}
$rx = 'anydesk|teamviewer|ultraviewer|screenconnect|connectwise control|logmein|splashtop|chrome remote desktop|chromoting|remoting_host|quickassist|\bvnc\b|realvnc|tightvnc|ultravnc|supremo|ammyy|aeroadmin|dwagent|dwservice|zoho assist|zohods|remote utilities|rutserv|getscreen|parsec|radmin|gotoassist|gotomypc'

Write-Log 'Scam checkup: looking for remote-control software...' 'STEP'
$keys = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*', 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*', 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*'
$installed = @(Get-ItemProperty $keys -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName })
foreach ($p in $installed) { if ($p.DisplayName -match $rx) { Add-Scam 'Alert' 'Remote-control software' (('{0} {1}' -f $p.DisplayName, $p.DisplayVersion).Trim()) } }
foreach ($pr in @(Get-Process -ErrorAction SilentlyContinue)) { $hay = ('{0} {1} {2}' -f $pr.ProcessName, $pr.Path, $pr.Description); if ($hay -match $rx) { Add-Scam 'Alert' 'Remote tool running now' ('{0} (PID {1})' -f $pr.ProcessName, $pr.Id) } }
foreach ($s in @(Get-CimInstance Win32_Service -ErrorAction SilentlyContinue)) { $hay = ('{0} {1} {2}' -f $s.Name, $s.DisplayName, $s.PathName); if ($hay -match $rx) { Add-Scam 'Alert' 'Remote tool service' ('{0} [{1}]' -f $s.DisplayName, $s.State) } }

Write-Log 'Checking recently installed programs...' 'STEP'
$cut = (Get-Date).AddDays(-30)
$uninstRoots = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall', 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall', 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'
$seenInst = @{}
foreach ($root in $uninstRoots) {
    foreach ($sk in (Get-ChildItem -LiteralPath $root -ErrorAction SilentlyContinue)) {
        $name = [string]$sk.GetValue('DisplayName'); if (-not $name) { continue }
        if ([int]$sk.GetValue('SystemComponent') -eq 1) { continue }
        # Prefer the key's last-write time (has the time of day); fall back to InstallDate (date only).
        $wt = Get-KeyWriteTime $sk
        $instRaw = [string]$sk.GetValue('InstallDate')
        $when = $null; $whenText = ''; $exact = $false
        if ($wt) { $when = $wt; $whenText = $wt.ToString('yyyy-MM-dd HH:mm'); $exact = $true }
        elseif ($instRaw -match '^\d{8}$') { try { $when = [datetime]::ParseExact($instRaw, 'yyyyMMdd', $null); $whenText = $when.ToString('yyyy-MM-dd') } catch { } }
        if (-not $when -or $when -lt $cut) { continue }
        $k = $name + '|' + $whenText; if ($seenInst.ContainsKey($k)) { continue }; $seenInst[$k] = $true
        $note = if ($exact) { 'installed/updated' } else { 'installed' }
        Add-Scam 'Review' 'Installed in last 30 days' ('{0}  ({1} {2})' -f $name, $note, $whenText)
    }
}

Write-Log 'Checking administrator accounts...' 'STEP'
try {
    $admins = @(Get-LocalGroupMember -Group 'Administrators' -ErrorAction Stop | ForEach-Object { $_.Name })
    if ($admins.Count) { Add-Scam 'Review' 'Administrator accounts' (('Members: ' + ($admins -join ', ')) + '  - confirm the customer recognizes each one.') }
} catch {
    try { $a2 = (net localgroup administrators) 2>&1 | Where-Object { $_ -and $_ -notmatch 'command completed|Alias name|Comment|Members|^-+$' }; if ($a2) { Add-Scam 'Review' 'Administrator accounts' (('Members: ' + (($a2 | ForEach-Object { $_.Trim() }) -join ', '))) } } catch { }
}

Write-Log 'Checking scheduled tasks created recently...' 'STEP'
try {
    foreach ($t in @(Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskPath -notlike '\Microsoft\*' })) {
        $dt = $null; if ($t.Date) { try { $dt = [datetime]$t.Date } catch { } }
        if ($dt -and $dt -ge $cut) { Add-Scam 'Review' 'New scheduled task' ('{0}{1}  ({2:yyyy-MM-dd})' -f $t.TaskPath, $t.TaskName, $dt) }
    }
} catch { }

Write-Log 'Checking startup (Run) entries...' 'STEP'
foreach ($rk in @('HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run', 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run', 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Run')) {
    if (-not (Test-Path -LiteralPath $rk)) { continue }
    $pp = Get-ItemProperty -LiteralPath $rk -ErrorAction SilentlyContinue
    if (-not $pp) { continue }
    foreach ($v in $pp.PSObject.Properties) {
        if ($v.Name -like 'PS*') { continue }
        $sev = if ([string]$v.Value -match $rx) { 'Alert' } else { 'Review' }
        Add-Scam $sev 'Startup entry' ('{0} = {1}' -f $v.Name, $v.Value)
    }
}

Write-Log 'Checking the hosts file...' 'STEP'
$hostsFile = Join-Path $env:SystemRoot 'System32\drivers\etc\hosts'
try {
    $bad = @(Get-Content -LiteralPath $hostsFile -ErrorAction Stop | Where-Object { $_ -and ($_ -notmatch '^\s*#') -and ($_ -match '\S') } | Where-Object { $_ -notmatch '^\s*(127\.0\.0\.1|::1)\s+localhost\s*$' })
    if ($bad.Count) { foreach ($l in ($bad | Select-Object -First 15)) { Add-Scam 'Alert' 'Hosts-file redirect' ($l.Trim()) } }
} catch { }

Write-Log 'Checking proxy settings...' 'STEP'
try {
    $ie = Get-ItemProperty -LiteralPath 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' -ErrorAction Stop
    if ([int]$ie.ProxyEnable -eq 1 -and $ie.ProxyServer) { Add-Scam 'Alert' 'Web proxy is ON' ('Proxy server: {0}  - scammers often set this to intercept traffic. Remove it if the customer did not.' -f $ie.ProxyServer) }
} catch { }
try { $wh = (netsh winhttp show proxy) 2>&1 | Out-String; if ($wh -notmatch 'Direct access' -and $wh -match 'Proxy Server') { $pm = [regex]::Match($wh, 'Proxy Server\(s\)\s*:\s*(.+)'); if ($pm.Success) { Add-Scam 'Alert' 'System (WinHTTP) proxy' ('Proxy: {0}' -f $pm.Groups[1].Value.Trim()) } } } catch { }

Write-Log 'Checking DNS servers...' 'STEP'
try {
    foreach ($d in @(Get-DnsClientServerAddress -AddressFamily IPv4 -ErrorAction Stop | Where-Object { $_.ServerAddresses })) {
        $srv = ($d.ServerAddresses -join ', ')
        if ($srv) { Add-Scam 'Review' 'DNS servers' ('{0}: {1}  - confirm these are the ISP/router or a known provider.' -f $d.InterfaceAlias, $srv) }
    }
} catch { }

Write-Log 'Checking firewall...' 'STEP'
try { $off = @(Get-NetFirewallProfile -ErrorAction Stop | Where-Object { [string]$_.Enabled -eq 'False' }); if ($off.Count) { Add-Scam 'Alert' 'Firewall is OFF' ('Off for: {0}  - turn it back on (Security tab).' -f (($off | ForEach-Object { $_.Name }) -join ', ')) } } catch { }

Write-Log 'Checking when Windows was installed...' 'STEP'
try {
    $osi = (Get-CimInstance Win32_OperatingSystem -ErrorAction Stop).InstallDate
    $when = $osi.ToString('yyyy-MM-dd HH:mm')
    if ($osi -ge (Get-Date).AddDays(-30)) { Add-Scam 'Review' 'Windows installed recently' ('{0}  - a very recent (re)install/reset can be normal, or a sign the PC was wiped. Confirm with the customer.' -f $when) }
    else { Add-Scam 'OK' 'Windows installed' $when }
} catch { }

if (-not ($rows | Where-Object { $_.Sev -ne 'OK' }).Count) { Add-Scam 'OK' 'Result' 'No common scam/remote-takeover indicators found. Still advise the customer to change important passwords from a trusted device if they shared any.' }
$Sync.ScamFindings = @($rows)
$alerts = @($rows | Where-Object { $_.Sev -eq 'Alert' }).Count
Write-Log ('Scam checkup complete - {0} finding(s), {1} alert(s).' -f @($rows).Count, $alerts) $(if ($alerts) { 'WARN' } else { 'DONE' })
'@
function Show-Scam {
    $lvScam.BeginUpdate(); $lvScam.Items.Clear()
    $rank = @{ Alert = 0; Review = 1; OK = 2 }
    foreach ($r in (@($Sync.ScamFindings) | Sort-Object { $rank[$_.Sev] })) {
        $it = New-Object System.Windows.Forms.ListViewItem([string]$r.Sev)
        [void]$it.SubItems.Add([string]$r.Area); [void]$it.SubItems.Add([string]$r.Detail); [void]$it.SubItems.Add([string]$r.When)
        if ($r.Sev -eq 'Alert') { $it.ForeColor = (RGB 200 60 60) } elseif ($r.Sev -eq 'Review') { $it.ForeColor = (RGB 181 71 8) } elseif ($r.Sev -eq 'OK') { $it.ForeColor = (RGB 20 140 70) }
        [void]$lvScam.Items.Add($it)
    }
    $lvScam.EndUpdate()
    $a = @($Sync.ScamFindings | Where-Object { $_.Sev -eq 'Alert' }).Count
    $rv = @($Sync.ScamFindings | Where-Object { $_.Sev -eq 'Review' }).Count
    $scamNote.Text = ('{0} alert(s), {1} to review. Red = strong indicator; amber = confirm with the customer. Nothing was changed - fix from the Security / Startup tabs.' -f $a, $rv)
}
$btnScamScan.Add_Click({ Start-Background -Script $ScamScanScript -Status 'Running scam checkup...' -OnComplete { Show-Scam } })
function Build-ScamReport {
    if (-not @($Sync.ScamFindings).Count) { Show-Msg 'Run the scam check first.'; return }
    Initialize-DataDirs
    function E($x) { [System.Net.WebUtility]::HtmlEncode([string]$x) }
    function WL($u) { $u = ([string]$u).Trim(); if (-not $u) { return '' }; if ($u -notmatch '^(?i)https?://') { $u = 'https://' + $u }; $d = ($u -replace '^(?i)https?://', '') -replace '/$', ''; return ('<a href="{0}">{1}</a>' -f (E $u), (E $d)) }
    $company = if ($script:Settings.CompanyName) { $script:Settings.CompanyName } else { 'Service Report' }
    $web = [string]$script:Settings.CompanyWebsite; $phone = [string]$script:Settings.CompanyPhone
    $tech = $txtTech.Text.Trim(); $cust = $txtCustomer.Text.Trim(); $ticket = $txtTicket.Text.Trim()
    $logo = Get-LogoDataUri
    $sectionsHtml = ''
    foreach ($g in @(@{ Sev = 'Alert'; Title = 'Strong indicators - check these'; Cls = 'now' }, @{ Sev = 'Review'; Title = 'Worth reviewing with the customer'; Cls = 'should' }, @{ Sev = 'OK'; Title = 'Notes'; Cls = 'opt' })) {
        $items = @($Sync.ScamFindings | Where-Object { $_.Sev -eq $g.Sev })
        if (-not $items.Count) { continue }
        $rowsH = ''
        foreach ($x in $items) { $rowsH += ('<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>' -f (E $x.Area), (E $x.Detail), (E $x.When)) }
        $sectionsHtml += ('<section><h2 class="{0}">{1}</h2><table><tr><th>Area</th><th>What we found</th><th>When found</th></tr>{2}</table></section>' -f $g.Cls, (E $g.Title), $rowsH)
    }
    $guide = @'
<section><h2 class="opt">If you think you were scammed - what to do</h2>
<ul class="recs">
<li>Disconnect any remote-control software the scammer used (we can remove it for you).</li>
<li>Change the passwords for your important accounts (email and banking first) from a different, trusted device - not the affected PC until it is cleaned.</li>
<li>Turn on two-step verification (2FA) where available.</li>
<li>If you shared card/bank details, made a payment, or bought gift cards: contact your bank or card issuer right away and watch for unauthorized charges.</li>
<li>If you gave money via gift cards or wire transfer, report it to the card issuer / your local authorities and the FTC at reportfraud.ftc.gov.</li>
<li>Keep this report. It lists what was found on the computer and when.</li>
</ul>
<p class="muted">This report lists what was found on the PC. It is informational and does not prove or rule out fraud by itself.</p></section>
'@
    $osInstall = ''
    try { $osInstall = (Get-CimInstance Win32_OperatingSystem -ErrorAction Stop).InstallDate.ToString('yyyy-MM-dd HH:mm') } catch { }
    $meta = ''
    if ($cust) { $meta += ('<tr><th>Customer</th><td>{0}</td></tr>' -f (E $cust)) }
    if ($ticket) { $meta += ('<tr><th>Ticket / job #</th><td>{0}</td></tr>' -f (E $ticket)) }
    $meta += ('<tr><th>Computer</th><td>{0}</td></tr>' -f (E $env:COMPUTERNAME))
    if ($osInstall) { $meta += ('<tr><th>Windows installed</th><td>{0}</td></tr>' -f (E $osInstall)) }
    $meta += ('<tr><th>Checked</th><td>{0}</td></tr>' -f (Get-Date -Format 'yyyy-MM-dd HH:mm'))
    if ($tech) { $meta += ('<tr><th>Checked by</th><td>{0}</td></tr>' -f (E $tech)) }
    $foot = (@((E $company), (WL $web), (E $phone)) | Where-Object { $_ }) -join ' - '
    $css = @"
body{font-family:'Segoe UI',Arial,sans-serif;margin:0;background:#f4f5f7;color:#1f2328}
header{background:#1f3a5f;color:#fff;padding:22px 32px}header h1{margin:0;font-size:24px}header p{margin:4px 0 0;opacity:.88}
header a{color:#cfe3ff} footer a{color:#2d6cdf} a{color:#2d6cdf}
main{max-width:900px;margin:0 auto;padding:16px}
section{background:#fff;border-radius:8px;padding:14px 18px;margin:14px 0;box-shadow:0 1px 3px rgba(0,0,0,.08)}
h2{font-size:17px;margin:0 0 10px}h2.now{color:#b42318}h2.should{color:#b54708}h2.opt{color:#1f3a5f}
table{border-collapse:collapse;width:100%;font-size:13px}th,td{text-align:left;padding:7px 9px;border-bottom:1px solid #e5e7eb;vertical-align:top}th{background:#f0f3f7}table.kv th{width:200px}
ul.recs{margin:4px 0;padding-left:20px}ul.recs li{margin:6px 0;line-height:1.45}.muted{color:#6b7280}
footer{text-align:center;color:#6b7280;font-size:12px;padding:20px}
@media print{body{background:#fff}section{box-shadow:none;border:1px solid #ddd}}
"@
    $html = @"
<!DOCTYPE html><html><head><meta charset="utf-8"><title>Security Check - $(E $env:COMPUTERNAME)</title><style>$css</style></head>
<body><header>$(if ($logo) { "<img src='$logo' alt='' style='max-height:50px;margin-bottom:8px;display:block'>" })<h1>$(E $company) - Security Check</h1><p>Possible-scam checkup for $(E $env:COMPUTERNAME)</p>$(if ($tech) { "<p>Checked by $(E $tech) on $(Get-Date -Format 'yyyy-MM-dd HH:mm')</p>" })</header>
<main><section><table class="kv">$meta</table></section>$sectionsHtml$guide</main><footer>$foot</footer></body></html>
"@
    $tag = if ($ticket) { ($ticket -replace '[^\w\-]', '') + '_' } else { '' }
    $path = Join-Path $ReportDir ('security-check_{0}{1}_{2:yyyyMMdd-HHmm}.html' -f $tag, $env:COMPUTERNAME, (Get-Date))
    Set-Content -LiteralPath $path -Value $html -Encoding UTF8
    Write-Ui ('Security-check report saved: {0}' -f $path) 'DONE'
    Start-Process $path
}
$btnScamReport.Add_Click({ Build-ScamReport })

# ---- Insights (small read-only viewers: blue screens, restarts, battery, startup, network) --
$tabIns = New-Ctl TabPage @{ Text = 'Insights'; Padding = (New-Pad 12) }
$insInfo = New-Ctl Label @{ Dock = 'Top'; Height = 36; Text = 'Read-only viewers that explain what has been happening on this PC. Pick one:' }
$insBtns = New-Ctl FlowLayoutPanel @{ Dock = 'Top'; Height = 40; WrapContents = $true; AutoSize = $false }
$btnInsBsod = New-Ctl Button @{ Text = 'Blue screens'; Width = 130; Height = 30; Margin = (New-Pad 0, 2, 6, 2) }
$btnInsRestart = New-Ctl Button @{ Text = 'Last restart && why'; Width = 150; Height = 30; Margin = (New-Pad 0, 2, 6, 2) }
$btnInsBattery = New-Ctl Button @{ Text = 'Battery use'; Width = 120; Height = 30; Margin = (New-Pad 0, 2, 6, 2) }
$btnInsBoot = New-Ctl Button @{ Text = 'Startup && shutdown'; Width = 160; Height = 30; Margin = (New-Pad 0, 2, 6, 2) }
$btnInsNet = New-Ctl Button @{ Text = 'Internet use'; Width = 120; Height = 30; Margin = (New-Pad 0, 2, 6, 2) }
$insBtns.Controls.AddRange([System.Windows.Forms.Control[]]@($btnInsBsod, $btnInsRestart, $btnInsBattery, $btnInsBoot, $btnInsNet))
$insNote = New-Ctl Label @{ Dock = 'Bottom'; Height = 46; Text = ''; Padding = (New-Pad 0, 6, 0, 0) }
$lvIns = New-Ctl ListView @{ Dock = 'Fill'; View = 'Details'; FullRowSelect = $true; GridLines = $true; HideSelection = $false; MultiSelect = $false }
$tabIns.Controls.Add($lvIns); $tabIns.Controls.Add($insNote); $tabIns.Controls.Add($insBtns); $tabIns.Controls.Add($insInfo)
$lvIns.BringToFront()
function Set-InsColumns($cols) { $lvIns.Columns.Clear(); foreach ($c in $cols) { [void]$lvIns.Columns.Add($c[0], $c[1]) } }

$BsodScanScript = @'
# Common bugcheck (stop) codes -> name + plain-English what-to-do. Keyed by normalized hex string
# (strip 0x and leading zeros, lowercase) so lookup never trips over Int32/Int64 or high codes.
$map = @{
    'a'   = @('IRQL_NOT_LESS_OR_EQUAL', 'Usually a faulty driver or bad RAM. Update/roll back recent drivers; run the RAM test.')
    '1a'  = @('MEMORY_MANAGEMENT', 'Often bad RAM or a driver. Run the RAM test; check for driver updates.')
    '1e'  = @('KMODE_EXCEPTION_NOT_HANDLED', 'Driver problem. Update/roll back drivers; check the faulting driver in BlueScreenView.')
    '3b'  = @('SYSTEM_SERVICE_EXCEPTION', 'Often a graphics or system driver. Update GPU/chipset drivers.')
    '50'  = @('PAGE_FAULT_IN_NONPAGED_AREA', 'Bad RAM or a driver referencing bad memory. Run the RAM test.')
    '7e'  = @('SYSTEM_THREAD_EXCEPTION_NOT_HANDLED', 'Driver fault. Update/roll back the faulting driver.')
    '7f'  = @('UNEXPECTED_KERNEL_MODE_TRAP', 'Often hardware/RAM or overclock. Run the RAM test; check temps.')
    '9c'  = @('MACHINE_CHECK_EXCEPTION', 'Hardware fault (CPU/power/heat). Check temperatures and power.')
    '9f'  = @('DRIVER_POWER_STATE_FAILURE', 'A driver mishandled sleep/resume. Update drivers (esp. storage/GPU/network).')
    'c2'  = @('BAD_POOL_CALLER', 'Driver memory bug. Update/roll back recent drivers.')
    'd1'  = @('DRIVER_IRQL_NOT_LESS_OR_EQUAL', 'Driver fault (often network/storage). Update that driver.')
    'ef'  = @('CRITICAL_PROCESS_DIED', 'System corruption. Run DISM + SFC (Repair tab); check the drive.')
    'f4'  = @('CRITICAL_OBJECT_TERMINATION', 'Often a failing drive. Check drive health / SMART.')
    '124' = @('WHEA_UNCORRECTABLE_ERROR', 'Hardware error (CPU/RAM/heat/power). Check temps; test RAM; reseat parts.')
    '133' = @('DPC_WATCHDOG_VIOLATION', 'Old storage driver or SSD firmware. Update SSD firmware + storage/chipset drivers.')
    '139' = @('KERNEL_SECURITY_CHECK_FAILURE', 'Driver or memory corruption. Update drivers; run RAM test + SFC.')
}
$dir = Join-Path $env:SystemRoot 'Minidump'
$dumpCount = 0; if (Test-Path -LiteralPath $dir) { $dumpCount = @(Get-ChildItem -LiteralPath $dir -Filter *.dmp -ErrorAction SilentlyContinue).Count }
$rows = New-Object System.Collections.ArrayList
try {
    $evts = @(Get-WinEvent -FilterHashtable @{ LogName = 'System'; Id = 1001; ProviderName = 'Microsoft-Windows-WER-SystemErrorReporting' } -MaxEvents 50 -ErrorAction Stop)
    foreach ($e in $evts) {
        $msg = [string]$e.Message
        $code = ''; $dump = ''; $name = ''; $hint = ''
        $m = [regex]::Match($msg, '0x[0-9A-Fa-f]{8}'); if ($m.Success) { $code = $m.Value }
        $dm = [regex]::Match($msg, 'saved in:\s*(.+?\.[dD][mM][pP])'); if ($dm.Success) { $dump = $dm.Groups[1].Value.Trim() }
        if ($code) { $key = ($code -replace '^0x', '').TrimStart('0').ToLower(); if (-not $key) { $key = '0' }; if ($map.ContainsKey($key)) { $name = $map[$key][0]; $hint = $map[$key][1] } }
        if (-not $hint) { $hint = 'Likely a driver or hardware issue - update drivers, run the RAM test, check temperatures. Open the dump in BlueScreenView for the faulting driver.' }
        [void]$rows.Add([pscustomobject]@{ Time = $e.TimeCreated.ToString('yyyy-MM-dd HH:mm'); Code = $code; Name = $name; Hint = $hint; Dump = $dump })
    }
} catch { }
$Sync.InsBsod = @($rows); $Sync.InsBsodDumps = $dumpCount
Write-Log ('Blue-screen scan: {0} crash event(s), {1} minidump file(s).' -f @($rows).Count, $dumpCount) 'DONE'
'@
function Show-Bsod {
    Set-InsColumns @(@('When', 120), @('Stop code', 110), @('Name', 240), @('Likely cause / what to do', 520), @('Dump file', 200))
    $lvIns.Items.Clear()
    foreach ($r in @($Sync.InsBsod)) {
        $it = New-Object System.Windows.Forms.ListViewItem([string]$r.Time)
        [void]$it.SubItems.Add([string]$r.Code); [void]$it.SubItems.Add([string]$r.Name); [void]$it.SubItems.Add([string]$r.Hint); [void]$it.SubItems.Add([string]$r.Dump)
        [void]$lvIns.Items.Add($it)
    }
    $n = @($Sync.InsBsod).Count
    if ($n) { $insNote.Text = ("{0} blue-screen crash event(s) recorded, {1} minidump file(s) in C:\Windows\Minidump. For the exact faulting driver, open a dump in BlueScreenView (Toolbox tab)." -f $n, $Sync.InsBsodDumps) }
    else { $insNote.Text = ("No blue-screen crash events recorded. ({0} minidump file(s) present.) That's good - no recent BSODs logged." -f $Sync.InsBsodDumps) }
}
$btnInsBsod.Add_Click({ Start-Background -Script $BsodScanScript -Status 'Reading blue-screen history...' -OnComplete { Show-Bsod } })

$RestartScanScript = @'
$rows = New-Object System.Collections.ArrayList
try {
    $evts = @(Get-WinEvent -FilterHashtable @{ LogName = 'System'; Id = @(1074, 6006, 6008, 41, 42, 6005, 1076) } -MaxEvents 80 -ErrorAction Stop)
    foreach ($e in $evts) {
        $msg = [string]$e.Message; $label = ''; $mean = ''
        switch ([int]$e.Id) {
            1074 {
                $label = 'Shutdown / restart requested'
                $proc = ''; $typ = ''; $rsn = ''
                $pm = [regex]::Match($msg, 'The process\s+(.+?)\s+\('); if ($pm.Success) { try { $proc = Split-Path $pm.Groups[1].Value -Leaf } catch { $proc = $pm.Groups[1].Value } }
                $tm = [regex]::Match($msg, 'Shutdown Type:\s*(\w+)'); if ($tm.Success) { $typ = $tm.Groups[1].Value }
                $rm = [regex]::Match($msg, 'reason:\s*(.+?)(\r|\n)'); if ($rm.Success) { $rsn = $rm.Groups[1].Value.Trim() }
                $t = if ($typ) { ($typ.Substring(0, 1).ToUpper() + $typ.Substring(1)) + ' ' } else { '' }
                $r = if ($rsn -and $rsn -notmatch 'No title') { ' - ' + $rsn } else { '' }
                $mean = ('{0}by {1}{2}' -f $t, $(if ($proc) { $proc } else { 'a process' }), $r)
            }
            6006 { $label = 'Clean shutdown'; $mean = 'Windows shut down normally.' }
            6005 { $label = 'System started'; $mean = 'Windows booted (event log started).' }
            6008 { $label = 'Unexpected shutdown'; $mean = 'The previous shutdown was unexpected - power loss, hard reset, or a crash.' }
            41   { $label = 'Kernel-Power (unexpected)'; $mean = 'Rebooted without a clean shutdown - crash, power loss, or forced reset. If a blue screen showed, check the Blue screens view.' }
            42   { $label = 'Entering sleep'; $mean = 'The PC went to sleep.' }
            1076 { $label = 'Unexpected-shutdown reason'; $mean = ($msg -split "`r?`n")[0] }
            default { $label = ('Event {0}' -f $e.Id); $mean = ($msg -split "`r?`n")[0] }
        }
        [void]$rows.Add([pscustomobject]@{ Time = $e.TimeCreated.ToString('yyyy-MM-dd HH:mm'); Event = $label; Meaning = $mean })
    }
} catch { }
$os = Get-CimInstance Win32_OperatingSystem -ErrorAction SilentlyContinue
$Sync.InsRestart = @($rows)
if ($os) { $Sync.InsLastBoot = $os.LastBootUpTime.ToString('yyyy-MM-dd HH:mm'); $u = (Get-Date) - $os.LastBootUpTime; $Sync.InsUptime = ('{0}d {1}h {2}m' -f $u.Days, $u.Hours, $u.Minutes) }
else { $Sync.InsLastBoot = ''; $Sync.InsUptime = '' }
Write-Log ('Restart history: {0} power event(s). Last boot {1} (up {2}).' -f @($rows).Count, $Sync.InsLastBoot, $Sync.InsUptime) 'DONE'
'@
function Show-Restart {
    Set-InsColumns @(@('When', 140), @('Event', 210), @('What it means', 620))
    $lvIns.Items.Clear()
    foreach ($r in @($Sync.InsRestart)) {
        $it = New-Object System.Windows.Forms.ListViewItem([string]$r.Time)
        [void]$it.SubItems.Add([string]$r.Event); [void]$it.SubItems.Add([string]$r.Meaning)
        if ($r.Event -match 'Unexpected|Kernel-Power') { $it.ForeColor = (RGB 200 60 60) }
        [void]$lvIns.Items.Add($it)
    }
    $insNote.Text = ('Last boot: {0}    Uptime: {1}    Red rows = the PC was not shut down cleanly (crash, power loss, or forced reset).' -f $Sync.InsLastBoot, $Sync.InsUptime)
}
$btnInsRestart.Add_Click({ Start-Background -Script $RestartScanScript -Status 'Reading restart history...' -OnComplete { Show-Restart } })

$BatteryScanScript = @'
# Battery charge / wear.
$b = Get-CimInstance Win32_Battery -ErrorAction SilentlyContinue | Select-Object -First 1
$design = 0; $full = 0
try { $design = [double]((Get-CimInstance -Namespace root\wmi -ClassName BatteryStaticData -ErrorAction Stop | Select-Object -First 1).DesignedCapacity) } catch { }
try { $full = [double]((Get-CimInstance -Namespace root\wmi -ClassName BatteryFullChargedCapacity -ErrorAction Stop | Select-Object -First 1).FullChargedCapacity) } catch { }
$wear = $null; if ($design -gt 0 -and $full -gt 0) { $wear = [math]::Round((1 - ($full / $design)) * 100) }
if (-not $b) {
    $summary = 'No battery detected - this looks like a desktop (or the battery is not reporting). Showing the busiest programs by CPU use.'
}
else {
    $charge = [int]$b.EstimatedChargeRemaining
    $onac = ($b.BatteryStatus -eq 2)
    $rt = [int64]$b.EstimatedRunTime
    $runtime = if ($onac -or $rt -ge 71582788 -or $rt -le 0) { 'on AC power' } else { ('~{0}h {1}m left on battery' -f [int]($rt / 60), ($rt % 60)) }
    $wearTxt = if ($wear -ne $null) { ('{0}% worn (full charge {1} of {2} mWh design)' -f $wear, [int]$full, [int]$design) } else { 'wear unknown' }
    $summary = ('Battery: {0}% charge, {1}; health {2}.' -f $charge, $runtime, $wearTxt)
}
# "Which programs" - top processes by cumulative CPU time (a reliable proxy for battery/heat use).
$procs = @(Get-Process -ErrorAction SilentlyContinue | Where-Object { $_.CPU } | Sort-Object CPU -Descending | Select-Object -First 15 |
    ForEach-Object { [pscustomobject]@{ Name = $_.ProcessName; Cpu = [math]::Round([double]$_.CPU); Mem = [math]::Round($_.WorkingSet64 / 1MB) } })
$Sync.InsBattSummary = $summary
$Sync.InsBattProcs = @($procs)
Write-Log ('Battery check done. {0}' -f $summary) 'DONE'
'@
function Show-Battery {
    Set-InsColumns @(@('Program (busiest first)', 330), @('CPU time used (s)', 150), @('Memory (MB)', 130))
    $lvIns.Items.Clear()
    foreach ($p in @($Sync.InsBattProcs)) {
        $it = New-Object System.Windows.Forms.ListViewItem([string]$p.Name)
        [void]$it.SubItems.Add([string]$p.Cpu); [void]$it.SubItems.Add([string]$p.Mem)
        [void]$lvIns.Items.Add($it)
    }
    $insNote.Text = ([string]$Sync.InsBattSummary + '   "CPU time" is cumulative since each program started - the top ones are the usual battery/heat culprits. Use Tools > Battery report for charge history, or Windows Settings > Battery usage for exact per-app drain.')
}
$btnInsBattery.Add_Click({ Start-Background -Script $BatteryScanScript -Status 'Checking battery and busiest programs...' -OnComplete { Show-Battery } })

$BootScanScript = @'
$log = 'Microsoft-Windows-Diagnostics-Performance/Operational'
function Xd($xml, $n) { $m = [regex]::Match($xml, ('<Data Name="{0}">(.*?)</Data>' -f [regex]::Escape($n))); if ($m.Success) { return $m.Groups[1].Value } return '' }
$rows = New-Object System.Collections.ArrayList
try {
    foreach ($e in @(Get-WinEvent -FilterHashtable @{ LogName = $log; Id = 100 } -MaxEvents 1 -ErrorAction Stop)) {
        $xml = $e.ToXml(); $main = [double](Xd $xml 'MainPathBootTime'); $boot = [double](Xd $xml 'BootTime')
        $sec = if ($main -gt 0) { [math]::Round($main / 1000, 1) } elseif ($boot -gt 0) { [math]::Round($boot / 1000, 1) } else { 0 }
        [void]$rows.Add([pscustomobject]@{ Time = $e.TimeCreated.ToString('yyyy-MM-dd HH:mm'); Type = 'Last boot time'; Detail = ('{0} seconds to reach the desktop' -f $sec) })
    }
} catch { }
foreach ($pair in @(@(101, 'App'), @(102, 'Driver'), @(103, 'Service'))) {
    try {
        foreach ($e in @(Get-WinEvent -FilterHashtable @{ LogName = $log; Id = $pair[0] } -MaxEvents 8 -ErrorAction Stop)) {
            $xml = $e.ToXml(); $name = Xd $xml 'Name'; if (-not $name) { $name = Xd $xml 'FriendlyName' }
            $tt = [double](Xd $xml 'TotalTime')
            [void]$rows.Add([pscustomobject]@{ Time = $e.TimeCreated.ToString('yyyy-MM-dd HH:mm'); Type = ('Slow startup - ' + $pair[1]); Detail = ('{0}  (+{1}s)' -f $name, [math]::Round($tt / 1000, 1)) })
        }
    } catch { }
}
try {
    foreach ($e in @(Get-WinEvent -FilterHashtable @{ LogName = $log; Id = 200 } -MaxEvents 1 -ErrorAction Stop)) {
        $xml = $e.ToXml(); $st = [double](Xd $xml 'ShutdownTime')
        [void]$rows.Add([pscustomobject]@{ Time = $e.TimeCreated.ToString('yyyy-MM-dd HH:mm'); Type = 'Last shutdown time'; Detail = ('{0} seconds to shut down' -f [math]::Round($st / 1000, 1)) })
    }
} catch { }
$Sync.InsBoot = @($rows)
Write-Log ('Startup/shutdown: {0} entry(ies) from the performance log.' -f @($rows).Count) 'DONE'
'@
function Show-Boot {
    Set-InsColumns @(@('When', 140), @('Type', 210), @('Detail', 610))
    $lvIns.Items.Clear()
    foreach ($r in @($Sync.InsBoot)) {
        $it = New-Object System.Windows.Forms.ListViewItem([string]$r.Time)
        [void]$it.SubItems.Add([string]$r.Type); [void]$it.SubItems.Add([string]$r.Detail)
        if ($r.Type -match 'Slow startup') { $it.ForeColor = (RGB 181 71 8) }
        [void]$lvIns.Items.Add($it)
    }
    if (-not @($Sync.InsBoot).Count) { $insNote.Text = 'No boot/shutdown performance data yet (the log fills over a few boots).' }
    else { $insNote.Text = 'From the Windows performance log. Amber "Slow startup" rows are what Windows blamed for adding boot time - disable or update the worst ones on the Startup tab.' }
}
$btnInsBoot.Add_Click({ Start-Background -Script $BootScanScript -Status 'Reading startup/shutdown timing...' -OnComplete { Show-Boot } })

$NetUseScript = @'
$rows = New-Object System.Collections.ArrayList
try {
    $conns = @(Get-NetTCPConnection -State Established -ErrorAction Stop)
    foreach ($g in ($conns | Group-Object OwningProcess | Sort-Object Count -Descending)) {
        $procId = $g.Name; $pname = ''
        try { $pname = (Get-Process -Id $procId -ErrorAction Stop).ProcessName } catch { $pname = ('(pid {0})' -f $procId) }
        $remotes = (@($g.Group | ForEach-Object { $_.RemoteAddress } | Where-Object { $_ -and $_ -ne '127.0.0.1' -and $_ -ne '::1' -and $_ -ne '0.0.0.0' } | Select-Object -Unique | Select-Object -First 4) -join ', ')
        [void]$rows.Add([pscustomobject]@{ Name = $pname; Count = $g.Count; Remotes = $remotes })
    }
} catch { }
# Per-adapter totals since boot + a short live rate sample.
$adapters = @(Get-NetAdapter -ErrorAction SilentlyContinue | Where-Object { $_.Status -eq 'Up' })
$first = @{}
foreach ($a in $adapters) { try { $st = Get-NetAdapterStatistics -Name $a.Name -ErrorAction Stop; $first[$a.Name] = @([double]$st.ReceivedBytes, [double]$st.SentBytes) } catch { } }
Start-Sleep -Milliseconds 1500
$parts = @()
foreach ($a in $adapters) {
    try {
        $st2 = Get-NetAdapterStatistics -Name $a.Name -ErrorAction Stop
        $r0 = $first[$a.Name][0]; $s0 = $first[$a.Name][1]
        $down = [math]::Round((($st2.ReceivedBytes - $r0) / 1KB) / 1.5)
        $up = [math]::Round((($st2.SentBytes - $s0) / 1KB) / 1.5)
        $parts += ('{0}: now {1} KB/s down / {2} KB/s up; since boot {3} GB down / {4} GB up' -f $a.Name, $down, $up, [math]::Round($st2.ReceivedBytes / 1GB, 2), [math]::Round($st2.SentBytes / 1GB, 2))
    } catch { }
}
$Sync.InsNetRows = @($rows); $Sync.InsNetSummary = ($parts -join '    ')
Write-Log ('Internet use: {0} program(s) with live connections.' -f @($rows).Count) 'DONE'
'@
function Show-NetUse {
    Set-InsColumns @(@('Program', 260), @('Active connections', 140), @('Connected to (sample)', 460))
    $lvIns.Items.Clear()
    foreach ($r in @($Sync.InsNetRows)) {
        $it = New-Object System.Windows.Forms.ListViewItem([string]$r.Name)
        [void]$it.SubItems.Add([string]$r.Count); [void]$it.SubItems.Add([string]$r.Remotes)
        [void]$lvIns.Items.Add($it)
    }
    $insNote.Text = ([string]$Sync.InsNetSummary + '    These are live connections right now; totals are since last boot. For monthly per-app data use, see Windows Settings > Network usage.')
}
$btnInsNet.Add_Click({ Start-Background -Script $NetUseScript -Status 'Checking internet use (live connections)...' -OnComplete { Show-NetUse } })

# ---- Recommendations (turn the diagnostics scan into a prioritized, actionable to-fix list) -
$tabRec = New-Ctl TabPage @{ Text = 'Recommendations'; Padding = (New-Pad 12) }
$recInfo = New-Ctl Label @{ Dock = 'Top'; Height = 42; Text = ("Scan the PC and get a plain-English, prioritized list of what to fix - grouped Fix now / Should do / Optional." + [Environment]::NewLine + "Tick the ones to do and press Fix checked, or build a recommendations report for the customer.") }
$recTop = New-Ctl FlowLayoutPanel @{ Dock = 'Top'; Height = 40; WrapContents = $false; AutoSize = $false }
$btnRecScan = New-Ctl Button @{ Text = 'Scan && recommend'; Width = 170; Height = 30; Margin = (New-Pad 0, 2, 8, 2) }
$btnRecFix  = New-Ctl Button @{ Text = 'Fix checked'; Width = 130; Height = 30; Margin = (New-Pad 2) }
$recTop.Controls.AddRange([System.Windows.Forms.Control[]]@($btnRecScan, $btnRecFix))
$recBtm = New-Ctl FlowLayoutPanel @{ Dock = 'Bottom'; Height = 44; Padding = (New-Pad 0, 6, 0, 0) }
$btnRecReport = New-Ctl Button @{ Text = 'Build recommendations report'; Width = 220; Height = 30 }
$recBtm.Controls.Add($btnRecReport)
$lvRec = New-Ctl ListView @{ Dock = 'Fill'; CheckBoxes = $true; View = 'Details'; FullRowSelect = $true; GridLines = $true; HideSelection = $false }
[void]$lvRec.Columns.Add('Recommendation', 620); [void]$lvRec.Columns.Add('One-click fix', 340)
$grpNow = New-Object System.Windows.Forms.ListViewGroup('Fix now', 'Fix now - important')
$grpShould = New-Object System.Windows.Forms.ListViewGroup('Should do', 'Should do - recommended')
$grpOpt = New-Object System.Windows.Forms.ListViewGroup('Optional', 'Optional - minor')
$lvRec.Groups.AddRange(@($grpNow, $grpShould, $grpOpt))
$tabRec.Controls.Add($lvRec); $tabRec.Controls.Add($recBtm); $tabRec.Controls.Add($recTop); $tabRec.Controls.Add($recInfo)
$lvRec.BringToFront()
$script:RecGroups = @{ 'Fix now' = $grpNow; 'Should do' = $grpShould; 'Optional' = $grpOpt }
$script:RecSevMap = @{ Critical = 'Fix now'; Warning = 'Should do'; Info = 'Optional' }
function Show-Recommendations {
    $lvRec.BeginUpdate(); $lvRec.Items.Clear()
    $rank = @{ Critical = 0; Warning = 1; Info = 2 }
    $any = $false
    foreach ($x in (@($Sync.Findings) | Where-Object { $_ -and $script:RecSevMap.ContainsKey($_.Severity) } | Sort-Object { $rank[$_.Severity] })) {
        $any = $true
        $fixIds = @($x.Fix | Where-Object { $_ -and $script:Actions.ContainsKey($_) })
        $fixNames = ($fixIds | ForEach-Object { $script:Actions[$_].Name }) -join ', '
        $it = New-Object System.Windows.Forms.ListViewItem([string]$x.Finding)
        [void]$it.SubItems.Add($(if ($fixNames) { $fixNames } else { 'Review / manual' }))
        $it.Group = $script:RecGroups[$script:RecSevMap[$x.Severity]]
        $it.Tag = [pscustomobject]@{ Fix = $fixIds }
        if ($fixIds.Count -and $x.Severity -ne 'Info') { $it.Checked = $true }
        [void]$lvRec.Items.Add($it)
    }
    $lvRec.EndUpdate()
    if (-not $any) { Write-Ui 'No recommendations yet - run a scan. If nothing shows after a scan, the PC looks healthy.' 'OK' }
}
$btnRecScan.Add_Click({ Start-Background -Script $DiagScript -Status 'Scanning for recommendations...' -OnComplete { Show-Findings; Show-Recommendations } })
$btnRecFix.Add_Click({
    $ids = @(); foreach ($it in $lvRec.CheckedItems) { if ($it.Tag -and $it.Tag.Fix) { $ids += @($it.Tag.Fix) } }
    $ids = @($ids | Where-Object { $_ } | Select-Object -Unique)
    if (-not $ids.Count) { Show-Msg 'Tick at least one recommendation that has a one-click fix.'; return }
    if ($ids -notcontains 'restorepoint' -and (Confirm-YesNo 'Create a restore point first? (recommended)')) { $ids = @('restorepoint') + $ids }
    Invoke-Actions -Ids $ids -Label 'Applying recommendations'
})
function Build-RecReport {
    $recs = @(@($Sync.Findings) | Where-Object { $_ -and $script:RecSevMap.ContainsKey($_.Severity) })
    if (-not $recs.Count) { Show-Msg 'Run a scan first (Scan & recommend).'; return }
    Initialize-DataDirs
    function E($x) { [System.Net.WebUtility]::HtmlEncode([string]$x) }
    function WL($u) { $u = ([string]$u).Trim(); if (-not $u) { return '' }; if ($u -notmatch '^(?i)https?://') { $u = 'https://' + $u }; $d = ($u -replace '^(?i)https?://', '') -replace '/$', ''; return ('<a href="{0}">{1}</a>' -f (E $u), (E $d)) }
    $company = if ($script:Settings.CompanyName) { $script:Settings.CompanyName } else { 'Service Report' }
    $web = [string]$script:Settings.CompanyWebsite; $phone = [string]$script:Settings.CompanyPhone
    $tech = $txtTech.Text.Trim(); $cust = $txtCustomer.Text.Trim(); $ticket = $txtTicket.Text.Trim()
    $logo = Get-LogoDataUri
    $groupsHtml = ''
    foreach ($g in @(@{ Sev = 'Critical'; Title = 'Fix now'; Cls = 'now' }, @{ Sev = 'Warning'; Title = 'Should do'; Cls = 'should' }, @{ Sev = 'Info'; Title = 'Optional'; Cls = 'opt' })) {
        $items = @($recs | Where-Object { $_.Severity -eq $g.Sev })
        if (-not $items.Count) { continue }
        $li = ''
        foreach ($x in $items) {
            $fixIds = @($x.Fix | Where-Object { $_ -and $script:Actions.ContainsKey($_) })
            $fixNames = ($fixIds | ForEach-Object { $script:Actions[$_].Name }) -join ', '
            $rec = (E $x.Finding) + $(if ($fixNames) { ' <span class="fix">Recommended: ' + (E $fixNames) + '</span>' } else { '' })
            $li += "<li>$rec</li>"
        }
        $groupsHtml += ('<section><h2 class="{0}">{1}</h2><ul class="recs">{2}</ul></section>' -f $g.Cls, (E $g.Title), $li)
    }
    $meta = ''
    if ($cust) { $meta += ('<tr><th>Customer</th><td>{0}</td></tr>' -f (E $cust)) }
    if ($ticket) { $meta += ('<tr><th>Ticket / job #</th><td>{0}</td></tr>' -f (E $ticket)) }
    $meta += ('<tr><th>Computer</th><td>{0}</td></tr>' -f (E $env:COMPUTERNAME))
    $meta += ('<tr><th>Date</th><td>{0}</td></tr>' -f (Get-Date -Format 'yyyy-MM-dd HH:mm'))
    if ($tech) { $meta += ('<tr><th>Technician</th><td>{0}</td></tr>' -f (E $tech)) }
    $foot = (@((E $company), (WL $web), (E $phone)) | Where-Object { $_ }) -join ' - '
    $css = @"
body{font-family:'Segoe UI',Arial,sans-serif;margin:0;background:#f4f5f7;color:#1f2328}
header{background:#1f3a5f;color:#fff;padding:22px 32px}header h1{margin:0;font-size:24px}header p{margin:4px 0 0;opacity:.88}
header a{color:#cfe3ff} footer a{color:#2d6cdf} a{color:#2d6cdf}
main{max-width:900px;margin:0 auto;padding:16px}
section{background:#fff;border-radius:8px;padding:14px 18px;margin:14px 0;box-shadow:0 1px 3px rgba(0,0,0,.08)}
h2{font-size:17px;margin:0 0 10px}h2.now{color:#b42318}h2.should{color:#b54708}h2.opt{color:#1f3a5f}
table{border-collapse:collapse;width:100%;font-size:13px}th,td{text-align:left;padding:7px 9px;border-bottom:1px solid #e5e7eb}th{background:#f0f3f7}table.kv th{width:200px}
ul.recs{margin:4px 0;padding-left:20px}ul.recs li{margin:6px 0;line-height:1.45}
.fix{color:#027a48;font-weight:600}
footer{text-align:center;color:#6b7280;font-size:12px;padding:20px}
@media print{body{background:#fff}section{box-shadow:none;border:1px solid #ddd}}
"@
    $html = @"
<!DOCTYPE html><html><head><meta charset="utf-8"><title>Our Recommendations - $(E $env:COMPUTERNAME)</title><style>$css</style></head>
<body><header>$(if ($logo) { "<img src='$logo' alt='' style='max-height:50px;margin-bottom:8px;display:block'>" })<h1>$(E $company) - Our Recommendations</h1><p>For $(E $env:COMPUTERNAME)</p>$(if ($tech) { "<p>Prepared by $(E $tech) on $(Get-Date -Format 'yyyy-MM-dd HH:mm')</p>" })</header>
<main><section><table class="kv">$meta</table></section>$groupsHtml</main><footer>$foot</footer></body></html>
"@
    $tag = if ($ticket) { ($ticket -replace '[^\w\-]', '') + '_' } else { '' }
    $path = Join-Path $ReportDir ('recommendations_{0}{1}_{2:yyyyMMdd-HHmm}.html' -f $tag, $env:COMPUTERNAME, (Get-Date))
    Set-Content -LiteralPath $path -Value $html -Encoding UTF8
    Write-Ui ('Recommendations report saved: {0}' -f $path) 'DONE'
    Start-Process $path
}
$btnRecReport.Add_Click({ Build-RecReport })

# ---- Printers (common repairs: spooler reset, clear jobs, set default, test page, re-add) ---
$tabPrinters = New-Ctl TabPage @{ Text = 'Printers'; Padding = (New-Pad 12) }
$prInfo = New-Ctl Label @{ Dock = 'Top'; Height = 44; Text = ("Fix the problems we see most: stuck print queues and flaky printers. Pick a printer below for the per-printer actions." + [Environment]::NewLine + "Spooler actions affect all printers; progress shows in the console.") }
$prTop = New-Ctl FlowLayoutPanel @{ Dock = 'Top'; Height = 40; WrapContents = $false; AutoSize = $false }
$btnPrRestart = New-Ctl Button @{ Text = 'Restart spooler'; Width = 140; Height = 30; Margin = (New-Pad 0, 2, 8, 2) }
$btnPrReset   = New-Ctl Button @{ Text = 'Full spooler reset (clears ALL jobs)'; Width = 250; Height = 30; Margin = (New-Pad 2) }
$prTop.Controls.AddRange([System.Windows.Forms.Control[]]@($btnPrRestart, $btnPrReset))
$prExtra = New-Ctl FlowLayoutPanel @{ Dock = 'Top'; Height = 40; WrapContents = $true; AutoSize = $false }
$btnPrAddIp   = New-Ctl Button @{ Text = 'Add by IP (9100)'; Width = 150; Height = 30; Margin = (New-Pad 0, 2, 6, 2) }
$btnPrDriver  = New-Ctl Button @{ Text = 'Remove printer + driver'; Width = 190; Height = 30; Margin = (New-Pad 0, 2, 6, 2) }
$btnPr11b     = New-Ctl Button @{ Text = 'Fix network printing (0x11b)'; Width = 210; Height = 30; Margin = (New-Pad 0, 2, 6, 2) }
$prExtra.Controls.AddRange([System.Windows.Forms.Control[]]@($btnPrAddIp, $btnPrDriver, $btnPr11b))
$prLinks = New-Ctl FlowLayoutPanel @{ Dock = 'Bottom'; Height = 40; Padding = (New-Pad 0, 4, 0, 0) }
$btnPrAdd    = New-Ctl Button @{ Text = 'Add printer...'; Width = 130; Height = 30 }
$btnPrSettings = New-Ctl Button @{ Text = 'Printers & scanners'; Width = 160; Height = 30 }
$btnPrServer = New-Ctl Button @{ Text = 'Print server properties'; Width = 180; Height = 30 }
$btnPrRefresh = New-Ctl Button @{ Text = 'Refresh'; Width = 90; Height = 30 }
$prLinks.Controls.AddRange([System.Windows.Forms.Control[]]@($btnPrAdd, $btnPrSettings, $btnPrServer, $btnPrRefresh))
$prActs = New-Ctl FlowLayoutPanel @{ Dock = 'Bottom'; Height = 44; Padding = (New-Pad 0, 6, 0, 0) }
$btnPrDefault = New-Ctl Button @{ Text = 'Set as default'; Width = 130; Height = 30 }
$btnPrClear   = New-Ctl Button @{ Text = 'Clear its jobs'; Width = 130; Height = 30 }
$btnPrTest    = New-Ctl Button @{ Text = 'Print test page'; Width = 140; Height = 30 }
$btnPrRemove  = New-Ctl Button @{ Text = 'Remove printer'; Width = 140; Height = 30 }
$prActs.Controls.AddRange([System.Windows.Forms.Control[]]@($btnPrDefault, $btnPrClear, $btnPrTest, $btnPrRemove))
$lvPrn = New-Ctl ListView @{ Dock = 'Fill'; View = 'Details'; FullRowSelect = $true; GridLines = $true; MultiSelect = $false; HideSelection = $false }
[void]$lvPrn.Columns.Add('Printer', 240); [void]$lvPrn.Columns.Add('Status', 90); [void]$lvPrn.Columns.Add('Default', 70); [void]$lvPrn.Columns.Add('Jobs', 55); [void]$lvPrn.Columns.Add('Port', 160); [void]$lvPrn.Columns.Add('Driver', 210)
$tabPrinters.Controls.Add($lvPrn); $tabPrinters.Controls.Add($prActs); $tabPrinters.Controls.Add($prLinks); $tabPrinters.Controls.Add($prExtra); $tabPrinters.Controls.Add($prTop); $tabPrinters.Controls.Add($prInfo)
$lvPrn.BringToFront()

$PrinterSpoolerResetScript = @'
Write-Log 'Resetting the print spooler...' 'STEP'
Stop-Svc 'Spooler'
Clear-Folder "$env:SystemRoot\System32\spool\PRINTERS" 'Print queue (all pending jobs)'
try { Set-Service -Name Spooler -StartupType Automatic -ErrorAction Stop } catch { }
Start-Svc 'Spooler'
$s = Get-Service Spooler -ErrorAction SilentlyContinue
if ($s -and $s.Status -eq 'Running') { Write-Log 'Print spooler reset and running. All queued jobs were cleared.' 'DONE' }
else { Write-Log 'Spooler did not start - check its dependencies (RPC).' 'WARN' }
'@

function Get-SelPrinter { if ($lvPrn.SelectedItems.Count) { return [string]$lvPrn.SelectedItems[0].Tag } return $null }
function Update-PrinterList {
    $lvPrn.Items.Clear()
    $def = ''
    try { $def = [string](Get-CimInstance Win32_Printer -Filter 'Default = TRUE' -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Name) } catch { }
    $printers = @()
    try { $printers = @(Get-Printer -ErrorAction Stop | Sort-Object Name) } catch { }
    if ($printers.Count) {
        foreach ($p in $printers) {
            $jobs = ''
            try { $jobs = [string](@(Get-PrintJob -PrinterName $p.Name -ErrorAction SilentlyContinue).Count) } catch { }
            $it = New-Object System.Windows.Forms.ListViewItem([string]$p.Name)
            [void]$it.SubItems.Add([string]$p.PrinterStatus)
            [void]$it.SubItems.Add($(if ($p.Name -eq $def) { 'Yes' } else { '' }))
            [void]$it.SubItems.Add($jobs)
            [void]$it.SubItems.Add([string]$p.PortName)
            [void]$it.SubItems.Add([string]$p.DriverName)
            $it.Tag = [string]$p.Name
            [void]$lvPrn.Items.Add($it)
        }
    }
    else {
        # Fallback for systems without the PrintManagement module.
        try {
            foreach ($p in (Get-CimInstance Win32_Printer -ErrorAction Stop | Sort-Object Name)) {
                $it = New-Object System.Windows.Forms.ListViewItem([string]$p.Name)
                [void]$it.SubItems.Add([string]$p.PrinterState); [void]$it.SubItems.Add($(if ($p.Default) { 'Yes' } else { '' })); [void]$it.SubItems.Add('')
                [void]$it.SubItems.Add([string]$p.PortName); [void]$it.SubItems.Add([string]$p.DriverName)
                $it.Tag = [string]$p.Name
                [void]$lvPrn.Items.Add($it)
            }
        } catch { }
    }
}
$btnPrRefresh.Add_Click({ Update-PrinterList })
$btnPrRestart.Add_Click({
    try { Restart-Service -Name Spooler -Force -ErrorAction Stop; Write-Ui 'Print Spooler restarted.' 'OK' }
    catch { Write-Ui ('Could not restart spooler: {0}' -f $_.Exception.Message) 'WARN' }
    Update-PrinterList
})
$btnPrReset.Add_Click({
    if ($Sync.Busy) { Show-Msg 'Another task is still running.'; return }
    if (-not (Confirm-YesNo 'Full spooler reset will stop the spooler and delete ALL pending print jobs on this PC, then restart it. Continue?')) { return }
    Start-Background -Script $PrinterSpoolerResetScript -Status 'Resetting print spooler...' -OnComplete { Update-PrinterList }
})
$btnPrDefault.Add_Click({
    $n = Get-SelPrinter; if (-not $n) { Show-Msg 'Pick a printer first.'; return }
    try { (New-Object -ComObject WScript.Network).SetDefaultPrinter($n); Write-Ui ('Default printer set to "{0}".' -f $n) 'OK' }
    catch { Write-Ui ('Could not set default: {0}' -f $_.Exception.Message) 'WARN' }
    Update-PrinterList
})
$btnPrClear.Add_Click({
    $n = Get-SelPrinter; if (-not $n) { Show-Msg 'Pick a printer first.'; return }
    try { Get-PrintJob -PrinterName $n -ErrorAction Stop | Remove-PrintJob -ErrorAction SilentlyContinue; Write-Ui ('Cleared the print queue for "{0}".' -f $n) 'OK' }
    catch { Write-Ui ('Could not clear jobs for "{0}": {1}' -f $n, $_.Exception.Message) 'WARN' }
    Update-PrinterList
})
$btnPrTest.Add_Click({
    $n = Get-SelPrinter; if (-not $n) { Show-Msg 'Pick a printer first.'; return }
    try {
        $cim = Get-CimInstance Win32_Printer -Filter ("Name='{0}'" -f ($n -replace "'", "''")) -ErrorAction Stop
        Invoke-CimMethod -InputObject $cim -MethodName PrintTestPage -ErrorAction Stop | Out-Null
        Write-Ui ('Sent a test page to "{0}".' -f $n) 'OK'
    } catch { Write-Ui ('Could not print a test page: {0}' -f $_.Exception.Message) 'WARN' }
})
$btnPrRemove.Add_Click({
    $n = Get-SelPrinter; if (-not $n) { Show-Msg 'Pick a printer first.'; return }
    if (-not (Confirm-YesNo ('Remove the printer "{0}" from this PC? (The driver stays installed so you can re-add it.)' -f $n))) { return }
    try { Remove-Printer -Name $n -ErrorAction Stop; Write-Ui ('Removed printer "{0}".' -f $n) 'OK' }
    catch { Write-Ui ('Could not remove "{0}": {1}' -f $n, $_.Exception.Message) 'WARN' }
    Update-PrinterList
})
$btnPrAdd.Add_Click({ try { Start-Process rundll32.exe 'printui.dll,PrintUIEntry /il' } catch { Start-Process 'ms-settings:printers' } })
$btnPrSettings.Add_Click({ try { Start-Process 'ms-settings:printers' } catch { } })
$btnPrServer.Add_Click({ try { Start-Process rundll32.exe 'printui.dll,PrintUIEntry /s /t2' } catch { } })
$btnPrAddIp.Add_Click({
    $ip = [Microsoft.VisualBasic.Interaction]::InputBox('Enter the printer''s IP address (a raw TCP/IP port on 9100 will be created):', 'Add printer by IP', '')
    $ip = $ip.Trim(); if (-not $ip) { return }
    if ($ip -notmatch '^\d{1,3}(\.\d{1,3}){3}$') { Show-Msg 'That is not a valid IPv4 address.'; return }
    $port = 'IP_' + $ip
    try {
        if (-not (Get-PrinterPort -Name $port -ErrorAction SilentlyContinue)) { Add-PrinterPort -Name $port -PrinterHostAddress $ip -ErrorAction Stop; Write-Ui ('Created TCP/IP port {0} -> {1}.' -f $port, $ip) 'OK' }
        else { Write-Ui ('TCP/IP port {0} already exists.' -f $port) 'OK' }
        Show-Msg ('Port "{0}" is ready. The Add Printer wizard will open - choose "Add a local printer", then "Use an existing port" and pick {0}, then select the driver.' -f $port)
        Start-Process rundll32.exe 'printui.dll,PrintUIEntry /il'
    } catch { Write-Ui ('Could not create the port: {0}' -f $_.Exception.Message) 'WARN' }
})
$btnPrDriver.Add_Click({
    $n = Get-SelPrinter; if (-not $n) { Show-Msg 'Pick the printer whose driver you want to remove.'; return }
    $drv = ''
    try { $drv = [string](Get-Printer -Name $n -ErrorAction Stop).DriverName } catch { }
    if (-not (Confirm-YesNo ("Remove the printer `"{0}`" AND its driver `"{1}`" from Windows?`r`n`r`nUse this for a corrupt driver - you'll reinstall it afterward. Other printers using the same driver will be affected." -f $n, $drv))) { return }
    try { Remove-Printer -Name $n -ErrorAction Stop; Write-Ui ('Removed printer "{0}".' -f $n) 'OK' } catch { Write-Ui ('Could not remove printer: {0}' -f $_.Exception.Message) 'WARN' }
    if ($drv) {
        try { Remove-PrinterDriver -Name $drv -RemoveFromDriverStore -ErrorAction Stop; Write-Ui ('Removed driver "{0}" (incl. driver store).' -f $drv) 'OK' }
        catch {
            try { Remove-PrinterDriver -Name $drv -ErrorAction Stop; Write-Ui ('Removed driver "{0}" (still in the driver store).' -f $drv) 'OK' }
            catch { Write-Ui ('Could not remove the driver (it may be in use by another printer - remove those first): {0}' -f $_.Exception.Message) 'WARN' }
        }
    }
    Update-PrinterList
})
$btnPr11b.Add_Click({
    if (-not (Confirm-YesNo ("Apply the fix for network-printing error 0x0000011b?`r`n`r`nThis sets RpcAuthnLevelPrivacyEnabled = 0 (a known workaround after certain Windows updates) and restarts the spooler. It slightly relaxes a print security mitigation.`r`n`r`nContinue?"))) { return }
    try {
        $rp = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Printers\RPC'
        if (-not (Test-Path -LiteralPath $rp)) { New-Item -Path $rp -Force | Out-Null }
        Set-ItemProperty -Path $rp -Name 'RpcAuthnLevelPrivacyEnabled' -Value 0 -Type DWord -Force
        try { Restart-Service -Name Spooler -Force -ErrorAction Stop } catch { }
        Write-Ui 'Applied the network-printing fix (0x0000011b) and restarted the spooler. Try printing to the shared/network printer again; a reboot can help if it still fails.' 'OK'
    } catch { Write-Ui ('Could not apply the fix: {0}' -f $_.Exception.Message) 'WARN' }
})
Update-PrinterList

# ---- Notes (capture customer info + what we see; save and push to the ticket) ---------------
$tabNotes = New-Ctl TabPage @{ Text = 'Notes'; Padding = (New-Pad 12) }
$ntInfo = New-Ctl Label @{ Dock = 'Top'; Height = 42; Text = ("Jot down what the customer told you and what you found / recommend. Uses the Customer / Ticket / Technician from the Report tab." + [Environment]::NewLine + "Save it as a note, or send it to the ticket.") }
$gbNtCust = New-Ctl GroupBox @{ Text = 'What the customer reported / asked for (and call-ins while you work)'; Dock = 'Top'; Height = 188; Padding = (New-Pad 8) }
$txtNotesCust = New-Ctl TextBox @{ Multiline = $true; ScrollBars = 'Vertical'; Dock = 'Fill'; Font = $Font; AcceptsReturn = $true }
$ntCustBar = New-Ctl FlowLayoutPanel @{ Dock = 'Bottom'; Height = 36; WrapContents = $false; AutoSize = $false; Padding = (New-Pad 0, 4, 0, 0) }
$lblNtQuick = New-Ctl Label @{ Text = 'Call-in:'; AutoSize = $true; Padding = (New-Pad 0, 7, 4, 0) }
$txtNtQuick = New-Ctl TextBox @{ Width = 440; Font = $Font }
$btnNtQuick = New-Ctl Button @{ Text = 'Add call-in note'; Width = 150; Height = 28 }
$ntCustBar.Controls.AddRange([System.Windows.Forms.Control[]]@($lblNtQuick, $txtNtQuick, $btnNtQuick))
$gbNtCust.Controls.Add($txtNotesCust); $gbNtCust.Controls.Add($ntCustBar); $txtNotesCust.BringToFront()
$Add_CallIn = {
    $t = $txtNtQuick.Text.Trim(); if (-not $t) { return }
    $line = '[{0:yyyy-MM-dd HH:mm}] {1}' -f (Get-Date), $t
    if ($txtNotesCust.TextLength -gt 0 -and $txtNotesCust.Text[-1] -ne "`n") { $txtNotesCust.AppendText([Environment]::NewLine) }
    $txtNotesCust.AppendText($line + [Environment]::NewLine)
    $txtNtQuick.Clear(); $txtNtQuick.Focus()
}
$btnNtQuick.Add_Click($Add_CallIn)
$txtNtQuick.Add_KeyDown({ if ($_.KeyCode -eq 'Return') { $_.SuppressKeyPress = $true; & $Add_CallIn } })
$gbNtObs = New-Ctl GroupBox @{ Text = 'What we found / recommend (tech notes)'; Dock = 'Fill'; Padding = (New-Pad 8) }
$txtNotesObs = New-Ctl TextBox @{ Multiline = $true; ScrollBars = 'Vertical'; Dock = 'Fill'; Font = $Font; AcceptsReturn = $true }
$ntObsBar = New-Ctl FlowLayoutPanel @{ Dock = 'Bottom'; Height = 38; Padding = (New-Pad 0, 4, 0, 0) }
$btnNtStamp = New-Ctl Button @{ Text = 'Insert timestamp'; Width = 150; Height = 28 }
$ntObsBar.Controls.Add($btnNtStamp)
$gbNtObs.Controls.Add($txtNotesObs); $gbNtObs.Controls.Add($ntObsBar); $txtNotesObs.BringToFront()
$ntBtns = New-Ctl FlowLayoutPanel @{ Dock = 'Bottom'; Height = 46; Padding = (New-Pad 0, 6, 0, 0) }
$btnNtSave   = New-Ctl Button @{ Text = 'Save note'; Width = 130; Height = 30 }
$btnNtTicket = New-Ctl Button @{ Text = 'Send to ticket...'; Width = 150; Height = 30 }
$btnNtClear  = New-Ctl Button @{ Text = 'Clear'; Width = 90; Height = 30 }
$ntBtns.Controls.AddRange([System.Windows.Forms.Control[]]@($btnNtSave, $btnNtTicket, $btnNtClear))
$tabNotes.Controls.Add($gbNtObs); $tabNotes.Controls.Add($gbNtCust); $tabNotes.Controls.Add($ntBtns); $tabNotes.Controls.Add($ntInfo)
$gbNtObs.BringToFront()

$btnNtStamp.Add_Click({
    $stamp = '[{0:yyyy-MM-dd HH:mm} {1}] ' -f (Get-Date), $script:Settings.TechName
    $pos = $txtNotesObs.SelectionStart
    $pre = if ($pos -gt 0 -and $txtNotesObs.Text[$pos - 1] -ne "`n") { [Environment]::NewLine } else { '' }
    $txtNotesObs.Text = $txtNotesObs.Text.Insert($pos, $pre + $stamp)
    $txtNotesObs.SelectionStart = $pos + ($pre + $stamp).Length; $txtNotesObs.Focus()
})
function Save-Notes([bool]$GoTicket) {
    $cust = $txtCustomer.Text.Trim(); $ticket = $txtTicket.Text.Trim(); $tech = $txtTech.Text.Trim()
    $c = $txtNotesCust.Text.Trim(); $o = $txtNotesObs.Text.Trim()
    if (-not $c -and -not $o) { Show-Msg 'Type some notes first.'; return }
    Initialize-DataDirs
    $company = if ($script:Settings.CompanyName) { $script:Settings.CompanyName } else { 'Service Notes' }
    $L = New-Object System.Collections.Generic.List[string]
    $L.Add(('{0} - Service Notes' -f $company))
    $L.Add(('Computer: {0}' -f $env:COMPUTERNAME))
    if ($cust) { $L.Add(('Customer: {0}' -f $cust)) }
    if ($ticket) { $L.Add(('Ticket / job #: {0}' -f $ticket)) }
    if ($tech) { $L.Add(('Technician: {0}' -f $tech)) }
    $L.Add(('Date: {0}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm')))
    $L.Add(''); $L.Add('WHAT THE CUSTOMER REPORTED'); $L.Add('--------------------------'); $L.Add($(if ($c) { $c } else { '(none noted)' }))
    $L.Add(''); $L.Add('WHAT WE FOUND / RECOMMEND'); $L.Add('-------------------------'); $L.Add($(if ($o) { $o } else { '(none noted)' }))
    $tag = if ($ticket) { ($ticket -replace '[^\w\-]', '') + '_' } else { '' }
    $path = Join-Path $ReportDir ('notes_{0}{1}_{2:yyyyMMdd-HHmm}.txt' -f $tag, $env:COMPUTERNAME, (Get-Date))
    Set-Content -LiteralPath $path -Value ($L.ToArray() -join [Environment]::NewLine) -Encoding UTF8
    Write-Ui ('Notes saved: {0}' -f $path) 'OK'
    if ($GoTicket) {
        Show-Tab $tabTracker
        if (Get-Command Update-SavedReports -ErrorAction SilentlyContinue) { Update-SavedReports }
        $leaf = Split-Path $path -Leaf
        foreach ($it in $lvSaved.Items) { if ($it.Text -eq $leaf) { $it.Checked = $true } }
        Show-Msg 'Your note was added to the reports list on the Repair Tracker tab and ticked. Enter the ticket number and upload code, then press "Upload ticked as text".'
    }
}
$btnNtSave.Add_Click({ Save-Notes $false })
$btnNtTicket.Add_Click({ Save-Notes $true })
$btnNtClear.Add_Click({ if (Confirm-YesNo 'Clear both note boxes?') { $txtNotesCust.Clear(); $txtNotesObs.Clear() } })

# ---- Startup manager (disable/enable startup programs, the Task Manager way - reversible) ---
$tabStartup = New-Ctl TabPage @{ Text = 'Startup'; Padding = (New-Pad 12) }
$suInfo = New-Ctl Label @{ Dock = 'Top'; Height = 54; Text = ("Trim what launches at sign-in to speed up boot. Tick items and press Disable - this is reversible (exactly what Task Manager does), nothing is deleted." + [Environment]::NewLine + "Changes take effect at the next sign-in. For deep startup cleanup (services, scheduled tasks, drivers) use Autoruns from the Toolbox.") }
$suTop = New-Ctl FlowLayoutPanel @{ Dock = 'Top'; Height = 40; WrapContents = $false; AutoSize = $false }
$btnSUDisable = New-Ctl Button @{ Text = 'Disable ticked'; Width = 140; Height = 30; Margin = (New-Pad 0, 2, 8, 2) }
$btnSUEnable  = New-Ctl Button @{ Text = 'Enable ticked'; Width = 130; Height = 30; Margin = (New-Pad 2) }
$btnSURefresh = New-Ctl Button @{ Text = 'Refresh'; Width = 90; Height = 30; Margin = (New-Pad 2) }
$suTop.Controls.AddRange([System.Windows.Forms.Control[]]@($btnSUDisable, $btnSUEnable, $btnSURefresh))
$suBtm = New-Ctl FlowLayoutPanel @{ Dock = 'Bottom'; Height = 42; Padding = (New-Pad 0, 6, 0, 0) }
$btnSUFolder = New-Ctl Button @{ Text = 'Open Startup folder'; Width = 170; Height = 30 }
$btnSUTask   = New-Ctl Button @{ Text = 'Open Task Manager'; Width = 160; Height = 30 }
$suBtm.Controls.AddRange([System.Windows.Forms.Control[]]@($btnSUFolder, $btnSUTask))
$lvSU = New-Ctl ListView @{ Dock = 'Fill'; CheckBoxes = $true; View = 'Details'; FullRowSelect = $true; GridLines = $true; HideSelection = $false }
[void]$lvSU.Columns.Add('Program', 220); [void]$lvSU.Columns.Add('Status', 80); [void]$lvSU.Columns.Add('Command / target', 360); [void]$lvSU.Columns.Add('Location', 170)
$tabStartup.Controls.Add($lvSU); $tabStartup.Controls.Add($suBtm); $tabStartup.Controls.Add($suTop); $tabStartup.Controls.Add($suInfo)
$lvSU.BringToFront()

$SuRunKeys = @(
    @{ Path = 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'; Appr = 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run'; Loc = 'Run (this user)' },
    @{ Path = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'; Appr = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run'; Loc = 'Run (all users)' },
    @{ Path = 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Run'; Appr = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run'; Loc = 'Run (all users, 32-bit)' }
)
$SuFolders = @(
    @{ Path = [Environment]::GetFolderPath('Startup'); Appr = 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\StartupFolder'; Loc = 'Startup folder (this user)' },
    @{ Path = [Environment]::GetFolderPath('CommonStartup'); Appr = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\StartupFolder'; Loc = 'Startup folder (all users)' }
)
function Get-SuState($apprPath, $name) {
    try { $v = (Get-ItemProperty -LiteralPath $apprPath -Name $name -ErrorAction Stop).$name; if ($v -and $v.Length -ge 1 -and ($v[0] -band 1)) { return 'Disabled' } } catch { }
    return 'Enabled'
}
function Set-SuState($apprPath, $name, [bool]$enable) {
    if (-not (Test-Path -LiteralPath $apprPath)) { New-Item -Path $apprPath -Force | Out-Null }
    if ($enable) { $bytes = [byte[]](2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) }
    else { $ft = [BitConverter]::GetBytes((Get-Date).ToFileTime()); $bytes = [byte[]]((@(3, 0, 0, 0) + $ft)) }
    New-ItemProperty -LiteralPath $apprPath -Name $name -Value $bytes -PropertyType Binary -Force | Out-Null
}
function Update-StartupList {
    $lvSU.Items.Clear()
    foreach ($rk in $SuRunKeys) {
        if (-not (Test-Path -LiteralPath $rk.Path)) { continue }
        $props = Get-ItemProperty -LiteralPath $rk.Path -ErrorAction SilentlyContinue
        if (-not $props) { continue }
        foreach ($p in $props.PSObject.Properties) {
            if ($p.Name -like 'PS*') { continue }
            $state = Get-SuState $rk.Appr $p.Name
            $it = New-Object System.Windows.Forms.ListViewItem([string]$p.Name)
            [void]$it.SubItems.Add($state); [void]$it.SubItems.Add([string]$p.Value); [void]$it.SubItems.Add($rk.Loc)
            $it.Tag = [pscustomobject]@{ Appr = $rk.Appr; Name = $p.Name }
            if ($state -eq 'Disabled') { $it.ForeColor = (RGB 150 150 150) }
            [void]$lvSU.Items.Add($it)
        }
    }
    foreach ($f in $SuFolders) {
        if (-not $f.Path -or -not (Test-Path -LiteralPath $f.Path)) { continue }
        foreach ($fi in (Get-ChildItem -LiteralPath $f.Path -File -ErrorAction SilentlyContinue | Where-Object { $_.Extension -match '^\.(lnk|exe|bat|cmd|vbs)$' })) {
            $state = Get-SuState $f.Appr $fi.Name
            $it = New-Object System.Windows.Forms.ListViewItem([string]$fi.BaseName)
            [void]$it.SubItems.Add($state); [void]$it.SubItems.Add([string]$fi.FullName); [void]$it.SubItems.Add($f.Loc)
            $it.Tag = [pscustomobject]@{ Appr = $f.Appr; Name = $fi.Name }
            if ($state -eq 'Disabled') { $it.ForeColor = (RGB 150 150 150) }
            [void]$lvSU.Items.Add($it)
        }
    }
}
function Set-StartupTicked([bool]$enable) {
    if (-not $lvSU.CheckedItems.Count) { Show-Msg 'Tick one or more startup programs first.'; return }
    $n = 0
    foreach ($it in $lvSU.CheckedItems) {
        try { Set-SuState $it.Tag.Appr $it.Tag.Name $enable; $n++ }
        catch { Write-Ui ('Could not change {0}: {1}' -f $it.Text, $_.Exception.Message) 'WARN' }
    }
    if ($n) { Write-Ui ('{0} {1} startup item(s). Takes effect at the next sign-in.' -f $(if ($enable) { 'Enabled' } else { 'Disabled' }), $n) 'OK' }
    Update-StartupList
}
$btnSUDisable.Add_Click({ Set-StartupTicked $false })
$btnSUEnable.Add_Click({ Set-StartupTicked $true })
$btnSURefresh.Add_Click({ Update-StartupList })
$btnSUFolder.Add_Click({ $p = [Environment]::GetFolderPath('Startup'); if ($p) { Start-Process explorer.exe $p } })
$btnSUTask.Add_Click({ try { Start-Process taskmgr.exe } catch { } })
Update-StartupList

# ---- Before / After (capture a snapshot, do the work, capture again, show the customer) -----
$tabBA = New-Ctl TabPage @{ Text = 'Before / After'; Padding = (New-Pad 12) }
$baInfo = New-Ctl Label @{ Dock = 'Top'; Height = 64; Text = ("Show the customer what your cleanup achieved. Capture BEFORE at the start, do your cleanup and repairs, then capture AFTER - the table fills in the improvement." + [Environment]::NewLine + "Build before/after report makes a branded HTML report (saved with your other reports, so it uploads to the ticket).") }
$lvBA = New-Ctl ListView @{ Dock = 'Fill'; View = 'Details'; FullRowSelect = $true; GridLines = $true; HeaderStyle = 'Nonclickable' }
[void]$lvBA.Columns.Add('Measure', 230); [void]$lvBA.Columns.Add('Before', 150); [void]$lvBA.Columns.Add('After', 150); [void]$lvBA.Columns.Add('Result', 240)
$baBtns = New-Ctl FlowLayoutPanel @{ Dock = 'Bottom'; Height = 46; Padding = (New-Pad 0, 6, 0, 0) }
$btnBABefore = New-Ctl Button @{ Text = 'Capture BEFORE'; Width = 150; Height = 30 }
$btnBAAfter  = New-Ctl Button @{ Text = 'Capture AFTER'; Width = 140; Height = 30 }
$btnBAReport = New-Ctl Button @{ Text = 'Build before/after report'; Width = 200; Height = 30 }
$btnBAClear  = New-Ctl Button @{ Text = 'Clear'; Width = 90; Height = 30 }
$chkBaSince  = New-Ctl CheckBox @{ Text = 'Count "After" errors only since Before'; AutoSize = $true; Checked = $true; Margin = (New-Pad 14, 8, 0, 0) }
$baBtns.Controls.AddRange([System.Windows.Forms.Control[]]@($btnBABefore, $btnBAAfter, $btnBAReport, $btnBAClear, $chkBaSince))
$tabBA.Controls.Add($lvBA); $tabBA.Controls.Add($baBtns); $tabBA.Controls.Add($baInfo); $lvBA.BringToFront()

$script:BAMetrics = @(
    @{ Key = 'FreePct';       Label = 'Free disk space';            Unit = '%';     Better = 'up';   Dec = 0 },
    @{ Key = 'FreeGB';        Label = 'Free space on system drive'; Unit = ' GB';   Better = 'up';   Dec = 1 },
    @{ Key = 'TempMB';        Label = 'Temporary / junk files';     Unit = ' MB';   Better = 'down'; Dec = 0 },
    @{ Key = 'Startup';       Label = 'Startup programs';           Unit = '';      Better = 'down'; Dec = 0 },
    @{ Key = 'Processes';     Label = 'Running processes';          Unit = '';      Better = 'down'; Dec = 0 },
    @{ Key = 'MemUsedPct';    Label = 'Memory in use';              Unit = '%';     Better = 'down'; Dec = 0 },
    @{ Key = 'CpuSec';        Label = 'CPU test (lower is faster)'; Unit = ' s';    Better = 'down'; Dec = 2 },
    @{ Key = 'DiskWriteMBps'; Label = 'Disk write speed';           Unit = ' MB/s'; Better = 'up';   Dec = 0 },
    @{ Key = 'DiskReadMBps';  Label = 'Disk read speed';            Unit = ' MB/s'; Better = 'up';   Dec = 0 }
)
# Security items are status strings, each with a test for what counts as a "good" value.
$script:BASecurity = @(
    @{ Key = 'SecAV';         Label = 'Antivirus';            Good = { param($v) $v -and $v -ne 'None detected' -and $v -ne 'Unknown' } },
    @{ Key = 'SecProtection'; Label = 'Real-time protection'; Good = { param($v) $v -eq 'On' } },
    @{ Key = 'SecUpToDate';   Label = 'Antivirus up to date'; Good = { param($v) $v -eq 'Yes' } },
    @{ Key = 'SecFirewall';   Label = 'Firewall';             Good = { param($v) [string]$v -like 'On*' } }
)
function Get-SecResult($m, $b, $a) {
    if (-not $b -or -not $a) { return 'n/a' }
    $bv = $b[$m.Key]; $av = $a[$m.Key]
    if ($null -eq $bv -and $null -eq $av) { return 'unknown' }
    $gb = & $m.Good $bv; $ga = & $m.Good $av
    if ($ga -and -not $gb) { return 'fixed' }
    if (-not $ga) { return 'needs attention' }
    return 'ok'
}
# Hardware health / errors. 'Good' = healthy / zero. Reuses Get-SecResult for the before/after verdict.
$script:BAHardware = @(
    @{ Key = 'HwDiskHealth'; Label = 'Drive health';                     Good = { param($v) [string]$v -eq 'Healthy' -or [string]$v -eq 'Unknown' } },
    @{ Key = 'HwSmart';      Label = 'Drives predicting failure (SMART)'; Good = { param($v) [int]$v -eq 0 } },
    @{ Key = 'HwBadDev';     Label = 'Devices with problems';             Good = { param($v) [int]$v -eq 0 } },
    @{ Key = 'HwWhea';       Label = 'Hardware errors logged';            Good = { param($v) [int]$v -eq 0 } },
    @{ Key = 'HwDiskErr';    Label = 'Disk / file-system errors logged';  Good = { param($v) [int]$v -eq 0 } }
)
function Format-BAValue($v, [int]$dec, [string]$unit) {
    if ($null -eq $v -or $v -eq '') { return '-' }
    if ($dec -gt 0) { return (('{0:N' + $dec + '}') -f [double]$v) + $unit }
    return ([string][int]$v) + $unit
}
# Returns @{ Text=...; Good=$true/$false/$null } describing the change for one metric.
function Get-BAResult($m, $b, $a) {
    if (-not $b -or -not $a) { return @{ Text = '-'; Good = $null } }
    $delta = [double]$a[$m.Key] - [double]$b[$m.Key]
    $eps = [math]::Pow(10, - $m.Dec) / 2
    if ([math]::Abs($delta) -lt $eps) { return @{ Text = 'no change'; Good = $null } }
    $good = if ($m.Better -eq 'up') { $delta -gt 0 } else { $delta -lt 0 }
    $sign = if ($delta -gt 0) { '+' } else { '-' }
    $mag = Format-BAValue ([math]::Abs($delta)) $m.Dec $m.Unit
    $word = if ($good) { 'better' } else { 'worse' }
    return @{ Text = ('{0}{1}  ({2})' -f $sign, $mag, $word); Good = $good }
}
function Update-BAView {
    $lvBA.Items.Clear()
    $b = $Sync.SnapBefore; $a = $Sync.SnapAfter
    foreach ($m in $script:BAMetrics) {
        $it = New-Object System.Windows.Forms.ListViewItem([string]$m.Label)
        [void]$it.SubItems.Add($(if ($b) { Format-BAValue $b[$m.Key] $m.Dec $m.Unit } else { '-' }))
        [void]$it.SubItems.Add($(if ($a) { Format-BAValue $a[$m.Key] $m.Dec $m.Unit } else { '-' }))
        [void]$it.SubItems.Add((Get-BAResult $m $b $a).Text)
        [void]$lvBA.Items.Add($it)
    }
    foreach ($grp in @(@{ Prefix = 'Security: '; Set = $script:BASecurity }, @{ Prefix = 'Hardware: '; Set = $script:BAHardware })) {
        foreach ($m in $grp.Set) {
            $bv = if ($b) { [string]$b[$m.Key] } else { '' }; if (-not $bv) { $bv = '-' }
            $av = if ($a) { [string]$a[$m.Key] } else { '' }; if (-not $av) { $av = '-' }
            $res = Get-SecResult $m $b $a
            $it = New-Object System.Windows.Forms.ListViewItem(($grp.Prefix + $m.Label))
            [void]$it.SubItems.Add($bv); [void]$it.SubItems.Add($av); [void]$it.SubItems.Add($res)
            if ($res -eq 'needs attention') { $it.ForeColor = (RGB 200 60 60) }
            elseif ($res -eq 'fixed') { $it.ForeColor = (RGB 20 140 70) }
            [void]$lvBA.Items.Add($it)
        }
    }
}
$btnBABefore.Add_Click({ Start-Background -Script $SnapshotScript -Vars @{ Slot = 'Before' } -Status 'Capturing BEFORE snapshot...' -OnComplete { Update-BAView } })
$btnBAAfter.Add_Click({
    if (-not $Sync.SnapBefore) { if (-not (Confirm-YesNo 'No BEFORE snapshot has been captured yet. Capture AFTER anyway?')) { return } }
    $vars = @{ Slot = 'After' }
    if ($chkBaSince.Checked -and $Sync.SnapBefore -and $Sync.SnapBefore.CapturedAt) { $vars.SinceIso = ([datetime]$Sync.SnapBefore.CapturedAt).ToString('o') }
    Start-Background -Script $SnapshotScript -Vars $vars -Status 'Capturing AFTER snapshot...' -OnComplete { Update-BAView }
})
$btnBAClear.Add_Click({ $Sync.SnapBefore = $null; $Sync.SnapAfter = $null; Update-BAView })
function Build-BAReport {
    $b = $Sync.SnapBefore; $a = $Sync.SnapAfter
    if (-not $b -or -not $a) { Show-Msg 'Capture a BEFORE snapshot and an AFTER snapshot first.'; return }
    Initialize-DataDirs
    function E($x) { [System.Net.WebUtility]::HtmlEncode([string]$x) }
    function WL($u) { $u = ([string]$u).Trim(); if (-not $u) { return '' }; if ($u -notmatch '^(?i)https?://') { $u = 'https://' + $u }; $d = ($u -replace '^(?i)https?://', '') -replace '/$', ''; return ('<a href="{0}">{1}</a>' -f (E $u), (E $d)) }
    $company = if ($script:Settings.CompanyName) { $script:Settings.CompanyName } else { 'Service Report' }
    $web = [string]$script:Settings.CompanyWebsite; $phone = [string]$script:Settings.CompanyPhone
    $tech = $txtTech.Text.Trim(); $cust = $txtCustomer.Text.Trim(); $ticket = $txtTicket.Text.Trim()
    $logo = Get-LogoDataUri
    # Highlights the customer cares about.
    $hi = @()
    $freed = [double]$a.FreeGB - [double]$b.FreeGB
    if ($freed -ge 0.1) { $hi += ('Freed {0:N1} GB of disk space' -f $freed) }
    $junk = [double]$b.TempMB - [double]$a.TempMB
    if ($junk -ge 1) { $hi += ('Removed {0:N0} MB of temporary / junk files' -f $junk) }
    $cut = [int]$b.Startup - [int]$a.Startup
    if ($cut -ge 1) { $hi += ('Reduced startup programs by {0}' -f $cut) }
    if ([double]$b.CpuSec -gt 0 -and [double]$a.CpuSec -lt [double]$b.CpuSec) { $hi += ('CPU test {0:N0}% faster' -f ((([double]$b.CpuSec - [double]$a.CpuSec) / [double]$b.CpuSec) * 100)) }
    # Security highlights.
    if ((Get-SecResult ($script:BASecurity | Where-Object { $_.Key -eq 'SecFirewall' }) $b $a) -eq 'fixed') { $hi += 'Turned the firewall back on' }
    if ((Get-SecResult ($script:BASecurity | Where-Object { $_.Key -eq 'SecProtection' }) $b $a) -eq 'fixed') { $hi += 'Turned on real-time antivirus protection' }
    if ((Get-SecResult ($script:BASecurity | Where-Object { $_.Key -eq 'SecUpToDate' }) $b $a) -eq 'fixed') { $hi += 'Brought antivirus up to date' }
    $appCount = @($Sync.AppsUpdated.ToArray()).Count
    if ($appCount -ge 1) { $hi += ('Updated {0} app{1}' -f $appCount, $(if ($appCount -ne 1) { 's' } else { '' })) }
    $hiHtml = if ($hi.Count) { '<ul class="hi">' + (($hi | ForEach-Object { '<li>' + (E $_) + '</li>' }) -join '') + '</ul>' } else { '<p class="muted">See the detailed comparison below.</p>' }
    # Comparison rows.
    $rowsHtml = ''
    foreach ($m in $script:BAMetrics) {
        $r = Get-BAResult $m $b $a
        $cls = if ($r.Good -eq $true) { 'good' } elseif ($r.Good -eq $false) { 'bad' } else { 'same' }
        $rowsHtml += ('<tr><td>{0}</td><td>{1}</td><td>{2}</td><td class="{3}">{4}</td></tr>' -f (E $m.Label), (E (Format-BAValue $b[$m.Key] $m.Dec $m.Unit)), (E (Format-BAValue $a[$m.Key] $m.Dec $m.Unit)), $cls, (E $r.Text))
    }
    # Security comparison rows.
    $secRowsHtml = ''
    foreach ($m in $script:BASecurity) {
        $res = Get-SecResult $m $b $a
        $ga = & $m.Good ($a[$m.Key])
        $cls = if ($res -eq 'fixed' -or ($res -eq 'ok' -and $ga)) { 'good' } elseif ($res -eq 'needs attention') { 'bad' } else { 'same' }
        $bv = [string]$b[$m.Key]; if (-not $bv) { $bv = '-' }
        $av = [string]$a[$m.Key]; if (-not $av) { $av = '-' }
        $secRowsHtml += ('<tr><td>{0}</td><td>{1}</td><td class="{2}">{3}</td><td class="{2}">{4}</td></tr>' -f (E $m.Label), (E $bv), $cls, (E $av), (E $res))
    }
    if ("$($b.SecDefAge)$($a.SecDefAge)") {
        $secRowsHtml += ('<tr><td>Antivirus definitions age (days)</td><td>{0}</td><td>{1}</td><td class="same"></td></tr>' -f (E ([string]$b.SecDefAge)), (E ([string]$a.SecDefAge)))
    }
    # Hardware health / errors rows (+ collect anything still needing attention for a heads-up).
    $hwRowsHtml = ''; $hwFlags = @()
    foreach ($m in $script:BAHardware) {
        $res = Get-SecResult $m $b $a
        $ga = & $m.Good ($a[$m.Key])
        $cls = if ($res -eq 'fixed' -or ($res -eq 'ok' -and $ga)) { 'good' } elseif ($res -eq 'needs attention') { 'bad' } else { 'same' }
        $bv = [string]$b[$m.Key]; if (-not $bv) { $bv = '-' }
        $av = [string]$a[$m.Key]; if (-not $av) { $av = '-' }
        $hwRowsHtml += ('<tr><td>{0}</td><td>{1}</td><td class="{2}">{3}</td><td class="{2}">{4}</td></tr>' -f (E $m.Label), (E $bv), $cls, (E $av), (E $res))
        if ($res -eq 'needs attention') { $hwFlags += ('{0}: {1}' -f $m.Label, $av) }
    }
    if ($a.HwBadDevList) { $hwRowsHtml += ('<tr><td>Problem devices</td><td colspan="3">{0}</td></tr>' -f (E ([string]$a.HwBadDevList))) }
    $hwNote = if ($hwFlags.Count) { '<p class="bad">Needs attention: ' + (E ($hwFlags -join '  |  ')) + '</p>' } else { '<p class="muted">No hardware problems detected.</p>' }
    if ($a.HwErrBasis) { $hwNote += ('<p class="muted">Logged-error counts for "After" cover {0}.</p>' -f (E ([string]$a.HwErrBasis))) }
    # Apps updated this session (name + old -> new version).
    $apps = @($Sync.AppsUpdated.ToArray())
    $appsHtml = ''
    if ($apps.Count) {
        $appsHtml = '<h2>Apps updated</h2><table><tr><th>App</th><th>From</th><th>To</th><th>When</th></tr>'
        foreach ($u in $apps) { $appsHtml += ('<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td></tr>' -f (E $u.Name), (E $(if ($u.From) { $u.From } else { '-' })), (E $(if ($u.To) { $u.To } else { 'latest' })), (E $u.Time)) }
        $appsHtml += '</table>'
    }
    # Work performed this session.
    $work = @($Sync.WorkDone.ToArray())
    $workHtml = ''
    if ($work.Count) {
        $workHtml = '<h2>Work performed</h2><table><tr><th>Time</th><th>Task</th><th>Result</th></tr>'
        foreach ($w in $work) { $workHtml += ('<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>' -f (E $w.Time), (E $w.Task), (E $w.Result)) }
        $workHtml += '</table>'
    }
    $meta = ''
    if ($cust) { $meta += ('<tr><th>Customer</th><td>{0}</td></tr>' -f (E $cust)) }
    if ($ticket) { $meta += ('<tr><th>Ticket / job #</th><td>{0}</td></tr>' -f (E $ticket)) }
    $meta += ('<tr><th>Computer</th><td>{0}</td></tr>' -f (E $env:COMPUTERNAME))
    $meta += ('<tr><th>Before</th><td>{0}</td></tr>' -f (E $b.Time))
    $meta += ('<tr><th>After</th><td>{0}</td></tr>' -f (E $a.Time))
    if ($tech) { $meta += ('<tr><th>Technician</th><td>{0}</td></tr>' -f (E $tech)) }
    $foot = (@((E $company), (WL $web), (E $phone)) | Where-Object { $_ }) -join ' - '
    $css = @"
body{font-family:'Segoe UI',Arial,sans-serif;margin:0;background:#f4f5f7;color:#1f2328}
header{background:#1f3a5f;color:#fff;padding:22px 32px}header h1{margin:0;font-size:24px}header p{margin:4px 0 0;opacity:.88}
main{max-width:900px;margin:0 auto;padding:16px}
section{background:#fff;border-radius:8px;padding:14px 18px;margin:14px 0;box-shadow:0 1px 3px rgba(0,0,0,.08)}
h2{font-size:17px;margin:0 0 10px;color:#1f3a5f}
table{border-collapse:collapse;width:100%;font-size:13px}th,td{text-align:left;padding:7px 9px;border-bottom:1px solid #e5e7eb}
th{background:#f0f3f7}table.kv th{width:200px}
td.good{color:#027a48;font-weight:600}td.bad{color:#b42318;font-weight:600}td.same{color:#6b7280}
header a{color:#cfe3ff} footer a{color:#2d6cdf} a{color:#2d6cdf}
ul.hi{margin:6px 0 0;padding-left:20px}ul.hi li{margin:3px 0;font-size:15px;color:#027a48;font-weight:600}
.muted{color:#6b7280}footer{text-align:center;color:#6b7280;font-size:12px;padding:20px}
@media print{body{background:#fff}section{box-shadow:none;border:1px solid #ddd}}
"@
    $html = @"
<!DOCTYPE html><html><head><meta charset="utf-8"><title>Before / After - $(E $env:COMPUTERNAME)</title><style>$css</style></head>
<body><header>$(if ($logo) { "<img src='$logo' alt='' style='max-height:50px;margin-bottom:8px;display:block'>" })<h1>$(E $company) - Before &amp; After</h1><p>Service results for $(E $env:COMPUTERNAME)</p>$(if ($tech) { "<p>Prepared by $(E $tech) on $(Get-Date -Format 'yyyy-MM-dd HH:mm')</p>" })</header>
<main>
<section><h2>What we did for you</h2>$hiHtml</section>
<section><table class="kv">$meta</table></section>
<section><h2>Before vs after</h2><table><tr><th>Measure</th><th>Before</th><th>After</th><th>Result</th></tr>$rowsHtml</table></section>
<section><h2>Security</h2><table><tr><th>Check</th><th>Before</th><th>After</th><th>Result</th></tr>$secRowsHtml</table></section>
<section><h2>Hardware health &amp; errors</h2><table><tr><th>Check</th><th>Before</th><th>After</th><th>Result</th></tr>$hwRowsHtml</table>$hwNote</section>
$(if ($appsHtml) { "<section>$appsHtml</section>" })
$(if ($workHtml) { "<section>$workHtml</section>" })
</main><footer>$foot</footer></body></html>
"@
    $tag = if ($ticket) { ($ticket -replace '[^\w\-]', '') + '_' } else { '' }
    $path = Join-Path $ReportDir ('before-after_{0}{1}_{2:yyyyMMdd-HHmm}.html' -f $tag, $env:COMPUTERNAME, (Get-Date))
    Set-Content -LiteralPath $path -Value $html -Encoding UTF8
    Write-Ui ('Before/after report saved: {0}' -f $path) 'DONE'
    Start-Process $path
}
$btnBAReport.Add_Click({ Build-BAReport })
Update-BAView

# ---- Power plans (restore High/Ultimate performance; switch plans; common tweaks) ----------
$tabPower = New-Ctl TabPage @{ Text = 'Power'; Padding = (New-Pad 12) }
$pwInfo = New-Ctl Label @{ Dock = 'Top'; Height = 50; Text = ("Windows 11 hides the High performance and Ultimate performance plans - the buttons below restore them and switch to them in one click." + [Environment]::NewLine + "Pick a plan and press Set active, or use the quick tweaks for bench work.") }
$pwTop = New-Ctl FlowLayoutPanel @{ Dock = 'Top'; Height = 40; WrapContents = $false; AutoSize = $false }
$btnPwHigh = New-Ctl Button @{ Text = 'Add / use High performance'; Width = 200; Height = 30; Margin = (New-Pad 0, 2, 8, 2) }
$btnPwUlt  = New-Ctl Button @{ Text = 'Add / use Ultimate performance'; Width = 210; Height = 30; Margin = (New-Pad 2) }
$btnPwRefresh = New-Ctl Button @{ Text = 'Refresh'; Width = 90; Height = 30; Margin = (New-Pad 2) }
$pwTop.Controls.AddRange([System.Windows.Forms.Control[]]@($btnPwHigh, $btnPwUlt, $btnPwRefresh))
$gbPwTweaks = New-Ctl GroupBox @{ Text = 'Quick tweaks (apply to the active plan, plugged-in / AC)'; Dock = 'Bottom'; Height = 96; Padding = (New-Pad 8) }
$flPwTweaks = New-Ctl FlowLayoutPanel @{ Dock = 'Fill'; AutoScroll = $true }
$gbPwTweaks.Controls.Add($flPwTweaks)
$pwActBar = New-Ctl FlowLayoutPanel @{ Dock = 'Bottom'; Height = 42; Padding = (New-Pad 0, 6, 0, 0) }
$btnPwSet = New-Ctl Button @{ Text = 'Set active'; Width = 120; Height = 30 }
$pwActBar.Controls.Add($btnPwSet)
$lvPower = New-Ctl ListView @{ Dock = 'Fill'; View = 'Details'; FullRowSelect = $true; GridLines = $true; MultiSelect = $false; HideSelection = $false }
[void]$lvPower.Columns.Add('Active', 60); [void]$lvPower.Columns.Add('Power plan', 300); [void]$lvPower.Columns.Add('GUID', 300)
$tabPower.Controls.Add($lvPower); $tabPower.Controls.Add($pwActBar); $tabPower.Controls.Add($gbPwTweaks); $tabPower.Controls.Add($pwTop); $tabPower.Controls.Add($pwInfo)
$lvPower.BringToFront()

$PwHighGuid = '8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c'
$PwUltGuid  = 'e9a42b02-d5df-448d-aa00-03f14749eb61'
function Invoke-PowerCfg([string[]]$PArgs) { try { return (& powercfg.exe @PArgs 2>&1 | Out-String) } catch { return ('ERROR: ' + $_.Exception.Message) } }
function Update-PowerList {
    $lvPower.Items.Clear()
    $out = Invoke-PowerCfg @('/list')
    foreach ($m in [regex]::Matches($out, 'Power Scheme GUID:\s*([0-9a-fA-F-]{36})\s*\(([^)]*)\)(\s*\*)?')) {
        $guid = $m.Groups[1].Value; $name = $m.Groups[2].Value.Trim(); $active = $m.Groups[3].Value.Trim() -eq '*'
        $it = New-Object System.Windows.Forms.ListViewItem($(if ($active) { 'active' } else { '' }))
        [void]$it.SubItems.Add($name); [void]$it.SubItems.Add($guid); $it.Tag = $guid
        if ($active) { $it.Selected = $true }
        [void]$lvPower.Items.Add($it)
    }
}
function Enable-PowerPlan([string]$BaseGuid, [string]$Label) {
    $null = Invoke-PowerCfg @('/setactive', $BaseGuid)
    if ($LASTEXITCODE -eq 0) { Write-Ui ('{0} is now the active power plan.' -f $Label) 'OK'; Update-PowerList; return }
    $dup = Invoke-PowerCfg @('-duplicatescheme', $BaseGuid)
    $mm = [regex]::Match($dup, '([0-9a-fA-F-]{36})')
    if ($mm.Success) {
        $null = Invoke-PowerCfg @('/setactive', $mm.Groups[1].Value)
        Write-Ui ('{0} added and set as the active power plan.' -f $Label) 'OK'
    }
    else { Write-Ui ('Could not add {0}. powercfg said: {1}' -f $Label, ($dup.Trim())) 'WARN' }
    Update-PowerList
    if (Get-Command Update-DashPower -ErrorAction SilentlyContinue) { Update-DashPower }
}
function Update-DashPower {
    if (-not $cmbDashPower) { return }
    $script:DashPowerLoading = $true
    $cmbDashPower.Items.Clear()
    $out = Invoke-PowerCfg @('/list')
    $haveHigh = $false; $haveUlt = $false; $activeIdx = -1; $idx = 0
    foreach ($m in [regex]::Matches($out, 'Power Scheme GUID:\s*([0-9a-fA-F-]{36})\s*\(([^)]*)\)(\s*\*)?')) {
        $guid = $m.Groups[1].Value; $name = $m.Groups[2].Value.Trim(); $active = $m.Groups[3].Value.Trim() -eq '*'
        if ($guid -ieq $PwHighGuid) { $haveHigh = $true }; if ($guid -ieq $PwUltGuid) { $haveUlt = $true }
        $disp = if ($active) { "$name  (active)" } else { $name }
        [void]$cmbDashPower.Items.Add([pscustomobject]@{ Display = $disp; Tag = $guid })
        if ($active) { $activeIdx = $idx }; $idx++
    }
    if (-not $haveHigh) { [void]$cmbDashPower.Items.Add([pscustomobject]@{ Display = 'High performance  (add & use)'; Tag = 'HIGH' }) }
    if (-not $haveUlt)  { [void]$cmbDashPower.Items.Add([pscustomobject]@{ Display = 'Ultimate performance  (add & use)'; Tag = 'ULT' }) }
    if ($activeIdx -ge 0) { $cmbDashPower.SelectedIndex = $activeIdx }
    $script:DashPowerLoading = $false
}
$btnPwRefresh.Add_Click({ Update-PowerList; Update-DashPower })
$btnPwHigh.Add_Click({ Enable-PowerPlan $PwHighGuid 'High performance' })
$btnPwUlt.Add_Click({ Enable-PowerPlan $PwUltGuid 'Ultimate performance' })
$btnPwSet.Add_Click({
    if (-not $lvPower.SelectedItems.Count) { Show-Msg 'Pick a power plan from the list first.'; return }
    $guid = [string]$lvPower.SelectedItems[0].Tag
    $null = Invoke-PowerCfg @('/setactive', $guid)
    Write-Ui ('Active power plan set to "{0}".' -f $lvPower.SelectedItems[0].SubItems[1].Text) 'OK'
    Update-PowerList
    Update-DashPower
})
$pwTweaks = @(
    @('Never sleep / display stays on', { Invoke-PowerCfg @('/change', 'monitor-timeout-ac', '0') | Out-Null; Invoke-PowerCfg @('/change', 'standby-timeout-ac', '0') | Out-Null; Write-Ui 'Set (AC): display never turns off, PC never sleeps.' 'OK' }),
    @('Display off 15 min, sleep 30 min', { Invoke-PowerCfg @('/change', 'monitor-timeout-ac', '15') | Out-Null; Invoke-PowerCfg @('/change', 'standby-timeout-ac', '30') | Out-Null; Write-Ui 'Set (AC): display off after 15 min, sleep after 30 min.' 'OK' }),
    @('Disable fast startup', { try { Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Power' -Name 'HiberbootEnabled' -Value 0 -Type DWord -Force; Write-Ui 'Fast startup disabled (takes effect after a full restart).' 'OK' } catch { Write-Ui ('Could not change fast startup: {0}' -f $_.Exception.Message) 'WARN' } }),
    @('Enable fast startup', { try { Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Power' -Name 'HiberbootEnabled' -Value 1 -Type DWord -Force; Write-Ui 'Fast startup enabled.' 'OK' } catch { Write-Ui ('Could not change fast startup: {0}' -f $_.Exception.Message) 'WARN' } }),
    @('Turn hibernation off', { Invoke-PowerCfg @('/hibernate', 'off') | Out-Null; Write-Ui 'Hibernation turned off (frees the hiberfil and disables fast startup).' 'OK' }),
    @('Turn hibernation on', { Invoke-PowerCfg @('/hibernate', 'on') | Out-Null; Write-Ui 'Hibernation turned on.' 'OK' })
)
foreach ($tw in $pwTweaks) {
    $b = New-Ctl Button @{ Text = $tw[0]; Width = 220; Height = 30; Margin = (New-Pad 3); Tag = $tw[1] }
    $b.Add_Click({ & $this.Tag }.GetNewClosure())
    $flPwTweaks.Controls.Add($b)
}
Update-PowerList
Update-DashPower

# ---- App Updates (update installed third-party apps via winget) ----------------------------
$tabUpdates = New-Ctl TabPage @{ Text = 'App Updates'; Padding = (New-Pad 12) }
$upInfo = New-Ctl Label @{ Dock = 'Top'; Height = 54; Text = ("Update the apps already installed on this PC (Chrome, Zoom, Acrobat, VLC and so on) using Windows' built-in winget." + [Environment]::NewLine + "Press Check for updates, untick anything you want to skip, then Update ticked - or Update all. Progress shows in the console below.") }
$upTop = New-Ctl FlowLayoutPanel @{ Dock = 'Top'; Height = 40; WrapContents = $false; AutoSize = $false }
$btnUpCheck    = New-Ctl Button @{ Text = 'Check for updates'; Width = 150; Height = 30; Margin = (New-Pad 0, 2, 8, 2) }
$btnUpTickAll  = New-Ctl Button @{ Text = 'Tick all'; Width = 90; Height = 30; Margin = (New-Pad 2) }
$btnUpTickNone = New-Ctl Button @{ Text = 'Untick all'; Width = 90; Height = 30; Margin = (New-Pad 2) }
$upTop.Controls.AddRange([System.Windows.Forms.Control[]]@($btnUpCheck, $btnUpTickAll, $btnUpTickNone))
$lvUp = New-Ctl ListView @{ Dock = 'Fill'; CheckBoxes = $true; View = 'Details'; FullRowSelect = $true; GridLines = $true; HideSelection = $false }
[void]$lvUp.Columns.Add('App', 260); [void]$lvUp.Columns.Add('Package id', 230); [void]$lvUp.Columns.Add('Installed', 110); [void]$lvUp.Columns.Add('Available', 110)
$lvUp.Add_Resize({ $w = $lvUp.ClientSize.Width - 230 - 110 - 110 - 6; if ($w -gt 160) { $lvUp.Columns[0].Width = $w } })
$upBtns = New-Ctl FlowLayoutPanel @{ Dock = 'Bottom'; Height = 46; Padding = (New-Pad 0, 6, 0, 0) }
$btnUpSel = New-Ctl Button @{ Text = 'Update ticked'; Width = 150; Height = 30 }
$btnUpAll = New-Ctl Button @{ Text = 'Update all'; Width = 130; Height = 30 }
$upBtns.Controls.AddRange([System.Windows.Forms.Control[]]@($btnUpSel, $btnUpAll))
$tabUpdates.Controls.Add($lvUp); $tabUpdates.Controls.Add($upBtns); $tabUpdates.Controls.Add($upTop); $tabUpdates.Controls.Add($upInfo)
$lvUp.BringToFront()
function Update-AppUpdateList {
    $lvUp.Items.Clear()
    foreach ($u in @($Sync.AppUpdates)) {
        $it = New-Object System.Windows.Forms.ListViewItem([string]$u.Name)
        [void]$it.SubItems.Add([string]$u.Id); [void]$it.SubItems.Add([string]$u.Current); [void]$it.SubItems.Add([string]$u.Available)
        $it.Tag = [string]$u.Id; $it.Checked = $true
        [void]$lvUp.Items.Add($it)
    }
    if (-not $lvUp.Items.Count) { Write-Ui 'No app updates available (or winget found none it can update).' 'OK' }
}
function Get-TickedUpdateIds { $out = @(); foreach ($it in $lvUp.CheckedItems) { if ($it.Tag) { $out += [string]$it.Tag } }; return @($out) }
$btnUpCheck.Add_Click({ Start-Background -Script $AppUpdateScanScript -Status 'Checking for app updates...' -OnComplete { Update-AppUpdateList } })
$btnUpTickAll.Add_Click({ foreach ($it in $lvUp.Items) { $it.Checked = $true } })
$btnUpTickNone.Add_Click({ foreach ($it in $lvUp.Items) { $it.Checked = $false } })
$btnUpSel.Add_Click({
    if ($Sync.Busy) { Show-Msg 'Another task is still running.'; return }
    $ids = Get-TickedUpdateIds
    if (-not $ids.Count) { Show-Msg 'Tick at least one app to update, or press Check for updates first.'; return }
    $targets = @(@($Sync.AppUpdates) | Where-Object { $ids -contains $_.Id })
    Start-Background -Script $AppUpdateRunScript -Vars @{ Ids = $ids; All = $false; Targets = $targets } -Status ('Updating {0} app(s)...' -f $ids.Count)
})
$btnUpAll.Add_Click({
    if ($Sync.Busy) { Show-Msg 'Another task is still running.'; return }
    if (-not (Confirm-YesNo 'Update every app on this PC that has an update available? This can take a while and some apps may close to update.')) { return }
    Start-Background -Script $AppUpdateRunScript -Vars @{ Ids = @(); All = $true; Targets = @($Sync.AppUpdates) } -Status 'Updating all apps...'
})

# ---- Navigation helpers: tabs are grouped, so selecting one means selecting its group + page.
function Show-Tab($page) {
    if (-not $page) { return }
    $inner = $page.Parent
    if ($inner -eq $script:tabs) { $script:tabs.SelectedTab = $page; return }
    if ($inner -and ($inner -is [System.Windows.Forms.TabControl])) {
        $grp = $inner.Parent
        if ($grp) { $script:tabs.SelectedTab = $grp }
        $inner.SelectedTab = $page
        return
    }
    $script:tabs.SelectedTab = $page
}
function Is-Showing($page) {
    $inner = $page.Parent
    if ($inner -eq $script:tabs) { return ($script:tabs.SelectedTab -eq $page) }
    if ($inner -and ($inner -is [System.Windows.Forms.TabControl])) { return (($inner.SelectedTab -eq $page) -and ($script:tabs.SelectedTab -eq $inner.Parent)) }
    return $false
}
# Build a top-level group tab that holds the given pages in an inner (top) tab strip.
function New-Group([string]$Text, [System.Windows.Forms.TabPage[]]$Pages) {
    $g = New-Ctl TabPage @{ Text = $Text; Padding = (New-Pad 0) }
    $inner = New-Ctl TabControl @{ Dock = 'Fill'; Padding = [System.Drawing.Point]::new(12, 4) }
    $inner.TabPages.AddRange($Pages)
    $g.Controls.Add($inner)
    return $g
}

# ---- Home / Start-here landing -------------------------------------------------------------
$tabHome = New-Ctl TabPage @{ Text = 'Home'; Padding = (New-Pad 16) }
$homeTitle = New-Ctl Label @{ Dock = 'Top'; Height = 58; Text = ("Welcome to BenchKit.  Fill in the Customer / Ticket at the top, then pick a starting point below." + [Environment]::NewLine + "A typical job: Capture BEFORE  ->  Diagnose & fix  ->  Capture AFTER  ->  Build the report.") }
$homeTitle.Font = New-Object System.Drawing.Font($Font.FontFamily, 10)
$homeFlow = New-Ctl FlowLayoutPanel @{ Dock = 'Fill'; AutoScroll = $true; Padding = (New-Pad 0, 8, 0, 0) }
$homeDefs = @(
    @('1.  Start job - capture BEFORE', { Show-Tab $tabBA; $btnBABefore.PerformClick() }),
    @('Full diagnostic scan', { Show-Tab $tabDiag; $btnScan.PerformClick() }),
    @('Recommendations (what to fix)', { Show-Tab $tabRec; $btnRecScan.PerformClick() }),
    @('Quick Tune-up', { Invoke-Actions -Ids $Presets['Quick Tune-up'] -Label 'Quick Tune-up' }),
    @('Scam / remote-access check', { Show-Tab $tabScam; $btnScamScan.PerformClick() }),
    @('Scan network devices', { Show-Tab $tabDevices }),
    @('Printers', { Show-Tab $tabPrinters }),
    @('Recover info / BitLocker key', { Show-Tab $tabInfo }),
    @('Back up data', { Show-Tab $tabBackup }),
    @('Finish - capture AFTER', { Show-Tab $tabBA; $btnBAAfter.PerformClick() }),
    @('Build customer report', { Show-Tab $tabReport }),
    @('Add a note', { Show-Tab $tabNotes })
)
foreach ($hd in $homeDefs) {
    $b = New-Ctl Button @{ Text = $hd[0]; Width = 250; Height = 54; Margin = (New-Pad 6); Tag = $hd[1]; TextAlign = 'MiddleLeft'; Padding = (New-Pad 12, 0, 0, 0) }
    $b.Add_Click({ & $this.Tag }.GetNewClosure())
    $homeFlow.Controls.Add($b)
}
$tabHome.Controls.Add($homeFlow); $tabHome.Controls.Add($homeTitle); $homeFlow.BringToFront()

# ---- Group the ~25 pages into a handful of sections -----------------------------------------
$grpHealth   = New-Group 'Health'   @($tabDash, $tabDiag, $tabRec, $tabIns, $tabBA)
$grpFix      = New-Group 'Fix'      @($tabRepair, $tabCleanup, $tabStartup, $tabPower, $tabProf)
$grpNetwork  = New-Group 'Network'  @($tabNetwork, $tabDevices, $tabPrinters)
$grpSecurity = New-Group 'Security' @($tabSecurity, $tabScam, $tabRemote)
$grpData     = New-Group 'Data'     @($tabInfo, $tabBackup)
$grpReport   = New-Group 'Report'   @($tabNotes, $tabReport, $tabTracker)
$grpTools    = New-Group 'Tools'    @($tabTools, $tabUpdates, $tabToolbox)
$tabs.TabPages.AddRange([System.Windows.Forms.TabPage[]]@($tabHome, $grpHealth, $grpFix, $grpNetwork, $grpSecurity, $grpData, $grpReport, $grpTools, $tabSet))
Set-Brand
$form.Controls.Add($split)
$form.Controls.Add($jobBar)
$form.Controls.Add($header)
$split.BringToFront()
#endregion

#region ---- Timers and window events --------------------------------------------------------
$uiTimer = New-Object System.Windows.Forms.Timer
$uiTimer.Interval = 250
$uiTimer.Add_Tick({
    $lines = New-Object System.Collections.Generic.List[string]
    $line = $null
    while ($Sync.Queue.TryDequeue([ref]$line)) { $lines.Add($line) }
    if ($lines.Count) { Write-UiLines $lines.ToArray() }

    if ($Sync.Busy) {
        $lblStatus.Text = $Sync.Status
        if ($prog.Style -eq 'Continuous' -and $Sync.Total -gt 0) { $prog.Value = [math]::Min($Sync.Total, [math]::Max(0, $Sync.Progress)) }
    }

    if ($script:BgHandle -and $script:BgHandle.IsCompleted) {
        try { [void]$script:BgPS.EndInvoke($script:BgHandle) } catch { Write-Ui $_.Exception.Message 'ERROR' }
        $errs = @($script:BgPS.Streams.Error | Select-Object -First 15)
        foreach ($e in $errs) { Write-Ui ([string]$e) 'ERROR' }
        $line = $null; $rest = New-Object System.Collections.Generic.List[string]
        while ($Sync.Queue.TryDequeue([ref]$line)) { $rest.Add($line) }
        if ($rest.Count) { Write-UiLines $rest.ToArray() }
        try { $script:BgPS.Runspace.Close(); $script:BgPS.Dispose() } catch { }
        $script:BgHandle = $null; $script:BgPS = $null
        $Sync.Busy = $false
        $prog.Style = 'Continuous'; $prog.Maximum = 100; $prog.Value = 100
        $lblStatus.Text = if ($Sync.Cancel) { 'Stopped' } else { 'Done - ready' }
        $btnStop.Enabled = $false
        if ($script:OnComplete) { $cb = $script:OnComplete; $script:OnComplete = $null; try { & $cb } catch { Write-Ui $_.Exception.Message 'ERROR' } }
    }
})

$monTimer = New-Object System.Windows.Forms.Timer
$monTimer.Interval = 2000
$monTimer.Add_Tick({ if ((Is-Showing $tabDash) -and $form.WindowState -ne 'Minimized') { Update-Monitor } })

foreach ($b in @($btnDashDiag, $btnDashTune, $btnDashRemote, $btnDashDeploy, $btnDashReport, $btnScan, $btnFix, $btnReport, $btnBackup, $btnFab, $btnInfoRun, $btnRemoteScan, $btnProfRun, $btnSetSave)) {
    if ($b) { [void]$script:PrimaryBtns.Add($b) }
}

$form.Add_Shown({
    try { $split.SplitterDistance = [int]($split.Height * 0.62) } catch { }
    Set-ControlTheme $form; Apply-Chrome
    # Ask who's working this bench (session only; defaults to the saved technician). Shows in the header and on reports.
    try {
        $who = [Microsoft.VisualBasic.Interaction]::InputBox("Who's working this bench? Your name appears in the app header and on every report.", 'Technician on duty', $script:Settings.TechName)
        $who = ($who -replace '[\r\n\t]+', ' ').Trim()
        if ($who) { $script:Settings.TechName = $who; if ($txtDefTech) { $txtDefTech.Text = $who }; if ($txtTech) { $txtTech.Text = $who } }
    } catch { }
    Set-Brand
    $lblPC.Text = Get-PCSummary
    Update-Monitor
    $uiTimer.Start(); $monTimer.Start()
    Write-Ui ('{0} {1} ready. Running as administrator. Session log: {2}' -f $AppName, $AppVersion, $LogFile) 'OK'
    Write-Ui 'Tip: start with Diagnostics > Scan now, or pick a Profile. Every task shows its exact commands before it runs.'
    # Hide the console window behind the app.
    try {
        Add-Type -Name ConsoleWin -Namespace BenchKit -MemberDefinition '[DllImport("kernel32.dll")] public static extern System.IntPtr GetConsoleWindow(); [DllImport("user32.dll")] public static extern bool ShowWindow(System.IntPtr h, int n);' -ErrorAction Stop
        [void][BenchKit.ConsoleWin]::ShowWindow([BenchKit.ConsoleWin]::GetConsoleWindow(), 0)
    } catch { }
})

$form.Add_FormClosing({
    if ($Sync.Busy) {
        if (-not (Confirm-YesNo 'A task is still running. Close anyway? (A Windows tool that is mid-run, like SFC or DISM, may keep going in the background.)')) { $_.Cancel = $true; return }
        try { [void]$script:BgPS.BeginStop($null, $null) } catch { }
    }
    $uiTimer.Stop(); $monTimer.Stop()
})
#endregion

[void]$form.ShowDialog()
$form.Dispose()
