[CmdletBinding()]
param(
    [switch]$StartWithWindows
)

$ErrorActionPreference = "Stop"
$Root = Split-Path -Parent $MyInvocation.MyCommand.Path
$SourceExe = Join-Path $Root "JVR Time Tracker.exe"
$InstallDir = Join-Path $env:LOCALAPPDATA "Programs\JVR Time Tracker"
$InstalledExe = Join-Path $InstallDir "JVR Time Tracker.exe"
$StartMenuDir = Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs\JVR Time Tracker"
$DesktopShortcut = Join-Path ([Environment]::GetFolderPath("Desktop")) "JVR Time Tracker.lnk"
$StartupShortcut = Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs\Startup\JVR Time Tracker.lnk"

function Set-CurrentUserRegistryValues([string]$ProviderPath, [hashtable]$Values) {
    $subKey = $ProviderPath.Substring("HKCU:\".Length)
    $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($subKey)
    if ($null -eq $key) {
        throw "Could not create registry key: $ProviderPath"
    }
    try {
        foreach ($name in $Values.Keys) {
            $key.SetValue($name, $Values[$name], [Microsoft.Win32.RegistryValueKind]::String)
        }
    } finally {
        $key.Dispose()
    }
}

if (-not (Test-Path -LiteralPath $SourceExe)) {
    throw "The packaged executable was not found: $SourceExe"
}

New-Item -ItemType Directory -Path $InstallDir -Force | Out-Null
New-Item -ItemType Directory -Path $StartMenuDir -Force | Out-Null

if (Test-Path -LiteralPath $InstalledExe) {
    $backup = Join-Path $InstallDir ("JVR Time Tracker.previous-{0}.exe" -f (Get-Date -Format "yyyyMMdd-HHmmss"))
    Copy-Item -LiteralPath $InstalledExe -Destination $backup -Force
}
Copy-Item -LiteralPath $SourceExe -Destination $InstalledExe -Force
Copy-Item -LiteralPath (Join-Path $Root "README.md") -Destination (Join-Path $InstallDir "README.md") -Force

$shell = New-Object -ComObject WScript.Shell
function New-Shortcut([string]$Path, [string]$Target, [string]$Arguments = "") {
    $shortcut = $shell.CreateShortcut($Path)
    $shortcut.TargetPath = $Target
    $shortcut.Arguments = $Arguments
    $shortcut.WorkingDirectory = $InstallDir
    $shortcut.IconLocation = "$Target,0"
    $shortcut.Description = "Track project time with JVR Time Tracker"
    $shortcut.Save()
}

New-Shortcut $DesktopShortcut $InstalledExe
New-Shortcut (Join-Path $StartMenuDir "JVR Time Tracker.lnk") $InstalledExe
New-Shortcut (Join-Path $StartMenuDir "Start a timer.lnk") $InstalledExe "--quick-start"
New-Shortcut (Join-Path $StartMenuDir "Stop active timer.lnk") $InstalledExe "--quick-stop"

if ($StartWithWindows) {
    New-Shortcut $StartupShortcut $InstalledExe
}

$commandStore = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell"
$commands = @(
    @{ Key = "JVRTimeTracker.Open"; Label = "Open time tracker"; Command = ('"{0}"' -f $InstalledExe) },
    @{ Key = "JVRTimeTracker.Start"; Label = "Start timer..."; Command = ('"{0}" --quick-start --context "%V"' -f $InstalledExe) },
    @{ Key = "JVRTimeTracker.Stop"; Label = "Stop active timer"; Command = ('"{0}" --quick-stop' -f $InstalledExe) }
)

foreach ($item in $commands) {
    $key = Join-Path $commandStore $item.Key
    New-Item -Path $key -Force | Out-Null
    Set-ItemProperty -Path $key -Name "MUIVerb" -Value $item.Label
    Set-ItemProperty -Path $key -Name "Icon" -Value $InstalledExe
    $commandKey = Join-Path $key "command"
    New-Item -Path $commandKey -Force | Out-Null
    Set-Item -Path $commandKey -Value $item.Command
}

$parents = @(
    "HKCU:\Software\Classes\DesktopBackground\Shell\JVRTimeTracker",
    "HKCU:\Software\Classes\Directory\Background\shell\JVRTimeTracker",
    "HKCU:\Software\Classes\Directory\shell\JVRTimeTracker",
    "HKCU:\Software\Classes\*\shell\JVRTimeTracker"
)
$subcommands = "JVRTimeTracker.Open;JVRTimeTracker.Start;JVRTimeTracker.Stop"
foreach ($key in $parents) {
    Set-CurrentUserRegistryValues $key @{
        "MUIVerb" = "JVR Time Tracker"
        "Icon" = $InstalledExe
        "SubCommands" = $subcommands
    }
}

$appPath = "HKCU:\Software\Microsoft\Windows\CurrentVersion\App Paths\JVRTimeTracker.exe"
New-Item -Path $appPath -Force | Out-Null
Set-Item -Path $appPath -Value $InstalledExe
Set-ItemProperty -Path $appPath -Name "Path" -Value $InstallDir

Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public static class ShellRefresh {
    [DllImport("shell32.dll")]
    public static extern void SHChangeNotify(int eventId, uint flags, IntPtr item1, IntPtr item2);
}
"@
[ShellRefresh]::SHChangeNotify(0x08000000, 0x1000, [IntPtr]::Zero, [IntPtr]::Zero)

Write-Host "JVR Time Tracker Windows integration installed for $env:USERNAME."
Write-Host "Installed application: $InstalledExe"
Write-Host "Right-click desktop, folders, or files and choose JVR Time Tracker."
Write-Host "On Windows 11, use Show more options to see classic context-menu commands."
Write-Host "Existing time data in LocalAppData was not changed."
