<#
.SYNOPSIS
    Sets system colors, wallpaper, and visual theme.

.DESCRIPTION
    Applies X9.cz visual identity: dark taskbar/Start with accent color #223B47
    (deep blue-gray), light app mode, no transparency. Wallpaper is set to a solid
    color matching the accent. BackInfo.exe (Step 07) overwrites the wallpaper with
    a live system info BMP on every logon - solid color is only the fallback.

.ITEMS
    system-tema-taskbar-start-dark: SystemUsesLightTheme=0 in Themes\Personalize. Dark mode for shell (taskbar, Start menu, Action Center, notification area). Does NOT affect application windows - those stay light. Reduces eye strain in dim environments.
    aplikacni-tema-light: AppsUseLightTheme=1. Application windows (File Explorer, Settings, Calculator, etc.) use white/light backgrounds. Majority of business applications (Office, browsers) also respect this and show light mode.
    accent-barva-223b47-tmave-modroseda: AccentColor DWORD = 0xFF473B22 (stored as ABGR: A=FF, B=47, G=3B, R=22). The deep blue-gray #223B47 is the X9.cz brand color, also used as the solid wallpaper background.
    accent-barva-na-start-a-taskbaru-ano: ColorPrevalence=1. Applies accent color to taskbar background and Start menu surface. The taskbar becomes the brand color instead of default black, creating a distinct recognizable look on X9.cz-deployed machines.
    pruhlednost-vypnuta: EnableTransparency=0. Disables Aero translucency on taskbar and Start. Improves text readability on the taskbar, reduces subtle GPU usage, and looks more professional/consistent on business machines.
    tapeta-jednobarevna-223b47-bez-obrazku: Wallpaper set to solid color #223B47 via SystemParametersInfo(SPI_SETDESKWALLPAPER). BackInfo.exe generates a BMP with hostname, username, OS, network info and sets it as wallpaper on every logon. Solid color = fallback only.
#>
param(
    [object]$Config,
    [string]$LogFile
)

$ErrorActionPreference = "Continue"

function Write-Log {
    param([string]$Message, [string]$Level = "INFO")
    $line = "[$(Get-Date -Format 'HH:mm:ss')] [$Level] $Message"
    Add-Content -Path $LogFile -Value $line -Encoding UTF8
}

# Accent color #223B47 stored as ABGR DWORD: 0xFF473B22
# A=FF B=47 G=3B R=22 -> 0xFF473B22 = 4283612962
$AccentColorABGR = 0xFF473B22

# Gradient colors (Windows generates these automatically but we set them explicitly)
# AccentPalette is 32 bytes - 8 shades of the accent color (BGRA each)
# We use the same color for all shades as a safe default
$AccentColorHex = "#223B47"

function Set-Reg {
    param([string]$Path, [string]$Name, $Value, [string]$Type = "DWord")
    try {
        if (-not (Test-Path $Path)) { New-Item -Path $Path -Force | Out-Null }
        Set-ItemProperty -Path $Path -Name $Name -Value $Value -Type $Type -Force
        Write-Log "  SET $Path\$Name = $Value" -Level OK
    }
    catch {
        Write-Log "  FAILED $Path\$Name - $_" -Level ERROR
    }
}

function Apply-ThemeSettings {
    param([string]$HiveRoot)  # "HKCU:" or "Registry::HKU\DefaultProfile"

    # -----------------------------------------------------------------------
    # System theme - Dark (taskbar, Start, action center)
    # -----------------------------------------------------------------------
    Set-Reg -Path "$HiveRoot\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize" `
            -Name "SystemUsesLightTheme" -Value 0

    # -----------------------------------------------------------------------
    # App theme - Light
    # -----------------------------------------------------------------------
    Set-Reg -Path "$HiveRoot\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize" `
            -Name "AppsUseLightTheme" -Value 1

    # -----------------------------------------------------------------------
    # Accent color on Start and taskbar
    # -----------------------------------------------------------------------
    Set-Reg -Path "$HiveRoot\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize" `
            -Name "ColorPrevalence" -Value 1

    # -----------------------------------------------------------------------
    # Transparency effects - disabled
    # -----------------------------------------------------------------------
    Set-Reg -Path "$HiveRoot\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize" `
            -Name "EnableTransparency" -Value 0

    # -----------------------------------------------------------------------
    # Accent color
    # -----------------------------------------------------------------------
    Set-Reg -Path "$HiveRoot\Software\Microsoft\Windows\DWM" `
            -Name "AccentColor" -Value $AccentColorABGR -Type "DWord"

    Set-Reg -Path "$HiveRoot\Software\Microsoft\Windows\DWM" `
            -Name "ColorizationColor" -Value $AccentColorABGR -Type "DWord"

    Set-Reg -Path "$HiveRoot\Software\Microsoft\Windows\DWM" `
            -Name "ColorizationAfterglow" -Value $AccentColorABGR -Type "DWord"

    # Accent color on title bars and borders
    Set-Reg -Path "$HiveRoot\Software\Microsoft\Windows\DWM" `
            -Name "ColorPrevalence" -Value 1

    # -----------------------------------------------------------------------
    # Wallpaper - solid color #223B47 (fallback before DesktopInfo runs)
    # -----------------------------------------------------------------------
    # Background color as decimal RGB
    Set-Reg -Path "$HiveRoot\Control Panel\Colors" `
            -Name "Background" -Value "34 59 71" -Type "String"

    Set-Reg -Path "$HiveRoot\Control Panel\Desktop" `
            -Name "WallpaperStyle" -Value "0" -Type "String"

    Set-Reg -Path "$HiveRoot\Control Panel\Desktop" `
            -Name "TileWallpaper" -Value "0" -Type "String"

    # -----------------------------------------------------------------------
    # Desktop icons - show This PC
    # -----------------------------------------------------------------------
    Set-Reg -Path "$HiveRoot\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel" `
            -Name "{20D04FE0-3AEA-1069-A2D8-08002B30309D}" -Value 0
}

# -----------------------------------------------------------------------
# Load Default hive
# -----------------------------------------------------------------------
$hivePath = "C:\Users\Default\NTUSER.DAT"
$hiveKey  = "DefaultProfile"

Write-Log "Loading Default hive for personalization" -Level INFO

& reg unload "HKU\$hiveKey" 2>&1 | Out-Null
$loadResult = & reg load "HKU\$hiveKey" $hivePath 2>&1
if ($LASTEXITCODE -ne 0) {
    Write-Log "Failed to load Default hive: $loadResult" -Level ERROR
    Write-Log "Applying personalization to current user only" -Level WARN

    Write-Log "Applying theme to current user (HKCU)" -Level STEP
    Apply-ThemeSettings -HiveRoot "HKCU:"

    # Set wallpaper via SystemParametersInfo for current user
    Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public class WallpaperHelper {
    [DllImport("user32.dll", CharSet=CharSet.Auto)]
    public static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
}
"@ -ErrorAction SilentlyContinue
    [WallpaperHelper]::SystemParametersInfo(20, 0, "", 3) | Out-Null
    exit 0
}

try {
    Write-Log "Applying theme to Default hive" -Level STEP
    Apply-ThemeSettings -HiveRoot "Registry::HKU\DefaultProfile"

    Write-Log "Applying theme to current user (HKCU)" -Level STEP
    Apply-ThemeSettings -HiveRoot "HKCU:"
}
finally {
    [GC]::Collect()
    [GC]::WaitForPendingFinalizers()
    Start-Sleep -Milliseconds 500

    $unloadResult = & reg unload "HKU\$hiveKey" 2>&1
    if ($LASTEXITCODE -eq 0) {
        Write-Log "Default hive unloaded" -Level OK
    } else {
        Write-Log "Failed to unload Default hive: $unloadResult" -Level ERROR
    }
}

# -----------------------------------------------------------------------
# Apply wallpaper (solid color) to current desktop session
# -----------------------------------------------------------------------
Write-Log "Setting desktop wallpaper to solid color" -Level INFO

try {
    Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public class WallpaperHelper {
    [DllImport("user32.dll", CharSet=CharSet.Auto)]
    public static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
}
"@ -ErrorAction SilentlyContinue

    # SPI_SETDESKTOPWALLPAPER=20, SPIF_UPDATEINIFILE|SPIF_SENDCHANGE=3
    # Empty string = solid color defined in Control Panel\Colors\Background
    [WallpaperHelper]::SystemParametersInfo(20, 0, "", 3) | Out-Null
    Write-Log "  Desktop wallpaper updated" -Level OK
}
catch {
    Write-Log "  Failed to update wallpaper: $_" -Level WARN
}

Write-Log "Step 5 complete" -Level OK
