create_desktop_shortcut.ps1

<#PSScriptInfo
 
.VERSION 2.0.0
 
.GUID 5991d012-5e7c-4ad2-8ccf-cdb75a0fdc73
 
.AUTHOR waresoft
 
.COMPANYNAME waresoft
 
.COPYRIGHT (c) 2026 waresoft. All rights reserved.
 
.TAGS PowerShell Shortcut ShortcutCreator DesktopShortcut LNK Launcher GUI WPF FluentDesign Windows Desktop Utility Automation DarkMode UAC Elevation ExecutionPolicy HiddenWindow pwsh PowerShell7
 
.LICENSEURI https://opensource.org/licenses/MIT
 
.PROJECTURI https://github.com/2civics/PowerShell-Desktop-Shortcut-Creator
 
.RELEASENOTES
v2.0.0:
Complete ground-up UI rebuild from WinForms to WPF with Windows 11 Fluent Design.
- Fluent WPF Interface: Replaced WinForms with XAML-based Fluent UI using an INotifyPropertyChanged ThemeManager, Segoe Fluent Icons, rounded cards, slim scrollbars, and native high-DPI scaling.
- Live Adaptive Theme Sync: Added Auto / Dark / Light segmented pill switcher with live Windows theme change sync (UserPreferenceChanged), DWM dark title bars, and rounded window corners.
- Built-In Visual Icon Grid Picker: Added visual browsing and index filtering for .dll, .exe, and .ico files with quick presets for imageres.dll, shell32.dll, ddores.dll, and pifmgr.dll.
- Drag-and-Drop Support: Drop any .ps1 script directly onto the window to populate the target path and shortcut name.
- Zero-Dependency PowerShell 7.x Compilation: Removed System.Drawing dependencies from inline C# by passing explicit WPF assembly references and converting HICONs natively via Imaging.CreateBitmapSourceFromHIcon.
 
v1.2.1:
- Fixed PowerShell 7.x High-DPI & Multi-Resolution Rendering and rebuilt responsive 3-zone layout.
 
v1.2.0:
- Aligned PowerShell 5.1 / 7.x mode selection, Get-Pwsh7Info detection, inline status indicator, and background winget/GitHub MSI installation with PSGallery-Manager.
 
v1.1.0:
- Hid the PowerShell console window and added the Hidden window launch mode.
 
#>


#Requires -Version 5.1

<#
.SYNOPSIS
    GUI Utility to Create Desktop Shortcuts for PowerShell Scripts (WPF Fluent UI + PS 5.1 & 7.x + Dark Mode + Auto-Elevating)
.DESCRIPTION
    A standalone, Windows 11 Fluent WPF GUI utility for creating .lnk Desktop shortcuts for PowerShell (.ps1) scripts, supporting Windows PowerShell 5.1 and PowerShell 7.x (pwsh.exe), adaptive Auto/Dark/Light themes, a visual icon grid picker with live preview, drag-and-drop, UAC elevation patching, and completely windowless background execution.
 
 
.PARAMETER Theme
    Initial theme mode: Auto, Dark, or Light. Defaults to Auto.
#>


[CmdletBinding()]
param(
    [ValidateSet('Auto', 'Dark', 'Light')]
    [string]$Theme = 'Auto'
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

# ==============================================================================
# 1. AUTO-ELEVATION, STA APARTMENT & HIDDEN CONSOLE CHECK
# ==============================================================================
$currentPrincipal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
$isAdmin = $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
$isPS51  = ($PSVersionTable.PSVersion.Major -lt 6)
$isSTA   = ([Threading.Thread]::CurrentThread.GetApartmentState() -eq 'STA')

$currentHostExe = (Get-Process -Id $PID).Path
if ([string]::IsNullOrWhiteSpace($currentHostExe) -or -not (Test-Path -LiteralPath $currentHostExe)) {
    $currentHostExe = if ($isPS51) {
        Join-Path -Path $env:SystemRoot -ChildPath 'System32\WindowsPowerShell\v1.0\powershell.exe'
    } else {
        Join-Path -Path $PSHOME -ChildPath 'pwsh.exe'
    }
}

if (-not $isAdmin -or ($isPS51 -and -not $isSTA)) {
    $relaunchArgs = [System.Collections.Generic.List[string]]::new()
    $relaunchArgs.Add('-NoProfile')
    $relaunchArgs.Add('-ExecutionPolicy')
    $relaunchArgs.Add('Bypass')
    $relaunchArgs.Add('-WindowStyle')
    $relaunchArgs.Add('Hidden')
    if ($isPS51) {
        $relaunchArgs.Add('-STA')
    }
    $relaunchArgs.Add('-File')
    $relaunchArgs.Add("`"$PSCommandPath`"")
    $relaunchArgs.Add('-Theme')
    $relaunchArgs.Add($Theme)

    $startParams = @{
        FilePath     = $currentHostExe
        ArgumentList = $relaunchArgs
        WindowStyle  = 'Hidden'
    }
    if (-not $isAdmin) {
        $startParams['Verb'] = 'RunAs'
    }

    Start-Process @startParams
    exit
}

Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName PresentationCore
Add-Type -AssemblyName WindowsBase
Add-Type -AssemblyName System.Xaml

# ==============================================================================
# 2. NATIVE WINDOWS 11 DWM, ICON EXTRACTOR & FLUENT THEME MANAGER (PS 5.1 + 7.x)
# ==============================================================================
if (-not ([System.Management.Automation.PSTypeName]'PSDeskCreator.ThemeManager').Type) {
    $wpfRefs = @(
        [System.Windows.Window].Assembly.Location,
        [System.Windows.Media.SolidColorBrush].Assembly.Location,
        [System.Windows.Media.Imaging.BitmapSource].Assembly.Location,
        [System.Windows.Interop.Imaging].Assembly.Location,
        [System.Windows.DependencyObject].Assembly.Location,
        [System.Windows.Markup.IUriContext].Assembly.Location,
        [System.ComponentModel.INotifyPropertyChanged].Assembly.Location,
        [System.ComponentModel.TypeConverter].Assembly.Location
    ) | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Select-Object -Unique

    Add-Type -ReferencedAssemblies $wpfRefs -TypeDefinition @"
using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
 
namespace PSDeskCreator {
    public static class NativeMethods {
        [DllImport("kernel32.dll")]
        public static extern IntPtr GetConsoleWindow();
 
        [DllImport("user32.dll")]
        public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
 
        [DllImport("user32.dll")]
        public static extern IntPtr GetAncestor(IntPtr hWnd, uint gaFlags);
 
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool DestroyIcon(IntPtr hIcon);
 
        [DllImport("dwmapi.dll", PreserveSig = true)]
        public static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);
 
        [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
        public static extern uint ExtractIconExW(
            string lpszFile,
            int nIconIndex,
            IntPtr[] phiconLarge,
            IntPtr[] phiconSmall,
            uint nIcons
        );
 
        public static void HideConsoleWindow() {
            IntPtr hwnd = GetConsoleWindow();
            if (hwnd != IntPtr.Zero) {
                ShowWindow(hwnd, 0);
                IntPtr root = GetAncestor(hwnd, 3);
                if (root != IntPtr.Zero && root != hwnd) {
                    ShowWindow(root, 0);
                }
            }
        }
 
        public static void ApplyWindowChromeAttributes(IntPtr hwnd, bool darkMode) {
            if (hwnd == IntPtr.Zero) return;
            int useDark = darkMode ? 1 : 0;
            if (DwmSetWindowAttribute(hwnd, 20, ref useDark, sizeof(int)) != 0) {
                DwmSetWindowAttribute(hwnd, 19, ref useDark, sizeof(int));
            }
            int cornerPref = 2;
            DwmSetWindowAttribute(hwnd, 33, ref cornerPref, sizeof(int));
        }
 
        public static int GetEmbeddedIconCount(string filePath) {
            if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath)) return 0;
            try {
                return (int)ExtractIconExW(filePath, -1, null, null, 0);
            }
            catch {
                return 0;
            }
        }
 
        public static BitmapSource ExtractIndexedIcon(string filePath, int index, int size) {
            if (string.IsNullOrEmpty(filePath)) return null;
            string expanded = Environment.ExpandEnvironmentVariables(filePath.Trim().Trim('"'));
            if (!File.Exists(expanded)) return null;
 
            IntPtr[] large = new IntPtr[1];
            IntPtr[] small = new IntPtr[1];
            try {
                uint extracted = ExtractIconExW(expanded, index, large, small, 1);
                IntPtr hIcon = (large[0] != IntPtr.Zero) ? large[0] : small[0];
                if (extracted > 0 && hIcon != IntPtr.Zero) {
                    BitmapSource bs = Imaging.CreateBitmapSourceFromHIcon(
                        hIcon,
                        Int32Rect.Empty,
                        BitmapSizeOptions.FromWidthAndHeight(size, size)
                    );
                    bs.Freeze();
                    return bs;
                }
            }
            catch { }
            finally {
                if (large[0] != IntPtr.Zero) DestroyIcon(large[0]);
                if (small[0] != IntPtr.Zero) DestroyIcon(small[0]);
            }
 
            if (expanded.EndsWith(".ico", StringComparison.OrdinalIgnoreCase)) {
                try {
                    BitmapFrame bf = BitmapFrame.Create(new Uri(expanded));
                    bf.Freeze();
                    return bf;
                }
                catch { }
            }
            return null;
        }
    }
 
    public class ThemeManager : INotifyPropertyChanged {
        public event PropertyChangedEventHandler PropertyChanged;
 
        public SolidColorBrush BgBrush { get; private set; }
        public SolidColorBrush SurfaceBrush { get; private set; }
        public SolidColorBrush CardBrush { get; private set; }
        public SolidColorBrush CardHoverBrush { get; private set; }
        public SolidColorBrush InputBrush { get; private set; }
        public SolidColorBrush PreviewBgBrush { get; private set; }
        public SolidColorBrush PreviewFgBrush { get; private set; }
        public SolidColorBrush BorderBrush { get; private set; }
        public SolidColorBrush TextBrush { get; private set; }
        public SolidColorBrush MutedBrush { get; private set; }
        public SolidColorBrush AccentBrush { get; private set; }
        public SolidColorBrush AccentHoverBrush { get; private set; }
        public SolidColorBrush AccentTextBrush { get; private set; }
        public SolidColorBrush SelectedBgBrush { get; private set; }
        public SolidColorBrush SelectedBdBrush { get; private set; }
        public SolidColorBrush ScrollThumbBrush { get; private set; }
        public SolidColorBrush SuccessBrush { get; private set; }
        public SolidColorBrush WarningBrush { get; private set; }
        public SolidColorBrush ErrorBrush { get; private set; }
        public SolidColorBrush ElevationBgBrush { get; private set; }
        public SolidColorBrush ElevationFgBrush { get; private set; }
 
        public ThemeManager() {
            Configure(true, true);
        }
 
        private static SolidColorBrush MakeBrush(string hex) {
            string h = hex.TrimStart('#');
            byte a = 255;
            int offset = 0;
            if (h.Length == 8) {
                a = Convert.ToByte(h.Substring(0, 2), 16);
                offset = 2;
            }
            byte r = Convert.ToByte(h.Substring(offset, 2), 16);
            byte g = Convert.ToByte(h.Substring(offset + 2, 2), 16);
            byte b = Convert.ToByte(h.Substring(offset + 4, 2), 16);
            SolidColorBrush brush = new SolidColorBrush(Color.FromArgb(a, r, g, b));
            brush.Freeze();
            return brush;
        }
 
        private void OnPropertyChanged(string name) {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
 
        public void Configure(bool darkMode, bool isElevated) {
            if (darkMode) {
                BgBrush = MakeBrush("#121418");
                SurfaceBrush = MakeBrush("#1A1D24");
                CardBrush = MakeBrush("#21252E");
                CardHoverBrush = MakeBrush("#2A2F3B");
                InputBrush = MakeBrush("#161920");
                PreviewBgBrush = MakeBrush("#0F1116");
                PreviewFgBrush = MakeBrush("#BAE6FD");
                BorderBrush = MakeBrush("#2E3440");
                TextBrush = MakeBrush("#F3F4F6");
                MutedBrush = MakeBrush("#9CA3AF");
                AccentBrush = MakeBrush("#38BDF8");
                AccentHoverBrush = MakeBrush("#0EA5E9");
                AccentTextBrush = MakeBrush("#0B1120");
                SelectedBgBrush = MakeBrush("#1E3A52");
                SelectedBdBrush = MakeBrush("#38BDF8");
                ScrollThumbBrush = MakeBrush("#3B4252");
                SuccessBrush = MakeBrush("#4ADE80");
                WarningBrush = MakeBrush("#FACC15");
                ErrorBrush = MakeBrush("#F87171");
                ElevationBgBrush = isElevated ? MakeBrush("#14532D") : MakeBrush("#78350F");
                ElevationFgBrush = isElevated ? MakeBrush("#86EFAC") : MakeBrush("#FDE68A");
            } else {
                BgBrush = MakeBrush("#F1F5F9");
                SurfaceBrush = MakeBrush("#FFFFFF");
                CardBrush = MakeBrush("#FFFFFF");
                CardHoverBrush = MakeBrush("#F8FAFC");
                InputBrush = MakeBrush("#F8FAFC");
                PreviewBgBrush = MakeBrush("#F1F5F9");
                PreviewFgBrush = MakeBrush("#334155");
                BorderBrush = MakeBrush("#CBD5E1");
                TextBrush = MakeBrush("#0F172A");
                MutedBrush = MakeBrush("#64748B");
                AccentBrush = MakeBrush("#0284C7");
                AccentHoverBrush = MakeBrush("#0369A1");
                AccentTextBrush = MakeBrush("#FFFFFF");
                SelectedBgBrush = MakeBrush("#E0F2FE");
                SelectedBdBrush = MakeBrush("#0284C7");
                ScrollThumbBrush = MakeBrush("#CBD5E1");
                SuccessBrush = MakeBrush("#16A34A");
                WarningBrush = MakeBrush("#B45309");
                ErrorBrush = MakeBrush("#DC2626");
                ElevationBgBrush = isElevated ? MakeBrush("#DCFCE7") : MakeBrush("#FEF3C7");
                ElevationFgBrush = isElevated ? MakeBrush("#166534") : MakeBrush("#92400E");
            }
            OnPropertyChanged(string.Empty);
        }
    }
}
"@

}

[PSDeskCreator.NativeMethods]::HideConsoleWindow()

# ==============================================================================
# 3. SYSTEM, THEME & PWSH 7 DETECTION HELPERS
# ==============================================================================
function Get-WindowsIsDarkMode {
    try {
        $val = Get-ItemPropertyValue -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize' -Name 'AppsUseLightTheme' -ErrorAction Stop
        return ($val -eq 0)
    }
    catch {
        return $true
    }
}

function Resolve-UseDarkMode {
    param([string]$Mode)
    switch ($Mode) {
        'Dark'  { return $true }
        'Light' { return $false }
        default { return (Get-WindowsIsDarkMode) }
    }
}

function Get-Pwsh7Info {
    $foundPath = $null

    foreach ($root in @(
        'HKLM:\SOFTWARE\Microsoft\PowerShellCore\InstalledVersions',
        'HKLM:\SOFTWARE\WOW6432Node\Microsoft\PowerShellCore\InstalledVersions'
    )) {
        if (Test-Path -LiteralPath $root) {
            $subKeys = Get-ChildItem -LiteralPath $root -ErrorAction SilentlyContinue | Sort-Object PSChildName -Descending
            foreach ($sub in $subKeys) {
                $props = Get-ItemProperty -LiteralPath $sub.PSPath -ErrorAction SilentlyContinue
                if ($null -ne $props -and -not [string]::IsNullOrWhiteSpace($props.InstallLocation)) {
                    $candidate = Join-Path -Path $props.InstallLocation -ChildPath 'pwsh.exe'
                    if (Test-Path -LiteralPath $candidate) { $foundPath = $candidate; break }
                }
            }
        }
        if ($foundPath) { break }
    }

    if (-not $foundPath) {
        foreach ($appPathKey in @(
            'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\pwsh.exe',
            'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\pwsh.exe'
        )) {
            try {
                $appVal = (Get-ItemProperty -LiteralPath $appPathKey -ErrorAction Stop).'(default)'
                if (-not [string]::IsNullOrWhiteSpace($appVal)) {
                    $cleaned = $appVal.Trim('"')
                    if (Test-Path -LiteralPath $cleaned) { $foundPath = $cleaned; break }
                }
            } catch { }
        }
    }

    if (-not $foundPath) {
        $candidates = [System.Collections.Generic.List[string]]::new()
        if (-not [string]::IsNullOrWhiteSpace($env:ProgramFiles)) {
            $candidates.Add((Join-Path -Path $env:ProgramFiles -ChildPath 'PowerShell\7\pwsh.exe'))
        }
        if (-not [string]::IsNullOrWhiteSpace(${env:ProgramFiles(x86)})) {
            $candidates.Add((Join-Path -Path ${env:ProgramFiles(x86)} -ChildPath 'PowerShell\7\pwsh.exe'))
        }
        if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {
            $candidates.Add((Join-Path -Path $env:LOCALAPPDATA -ChildPath 'Microsoft\WindowsApps\pwsh.exe'))
        }
        foreach ($candidate in $candidates) {
            if (Test-Path -LiteralPath $candidate) { $foundPath = $candidate; break }
        }
    }

    if (-not $foundPath) {
        $cmd = Get-Command -Name 'pwsh.exe' -ErrorAction SilentlyContinue | Select-Object -First 1
        if ($null -ne $cmd -and (Test-Path -LiteralPath $cmd.Source)) { $foundPath = $cmd.Source }
    }

    if (-not $foundPath) { return $null }

    $iconPath = $foundPath
    if ($foundPath -like '*\Microsoft\WindowsApps\pwsh.exe') {
        try {
            $pkg = Get-AppxPackage -Name 'Microsoft.PowerShell' -ErrorAction SilentlyContinue | Select-Object -First 1
            if ($null -ne $pkg -and -not [string]::IsNullOrWhiteSpace($pkg.InstallLocation)) {
                $realExe = Join-Path -Path $pkg.InstallLocation -ChildPath 'pwsh.exe'
                if (Test-Path -LiteralPath $realExe) { $iconPath = $realExe }
            }
        } catch { }
    }

    return [PSCustomObject]@{ ExePath = $foundPath; IconPath = $iconPath }
}

$script:ActiveTimers = [System.Collections.Generic.List[System.Windows.Threading.DispatcherTimer]]::new()

function Invoke-AsyncTask {
    param(
        [Parameter(Mandatory)][scriptblock]$Work,
        [hashtable]$State = @{},
        [Parameter(Mandatory)][scriptblock]$OnComplete
    )

    $ps = [PowerShell]::Create()
    [void]$ps.AddScript($Work)
    $asyncResult = $ps.BeginInvoke()

    $timer = New-Object System.Windows.Threading.DispatcherTimer
    $timer.Interval = [TimeSpan]::FromMilliseconds(100)
    [void]$script:ActiveTimers.Add($timer)

    $timer.Add_Tick({
        if (-not $asyncResult.IsCompleted) { return }
        $timer.Stop()
        [void]$script:ActiveTimers.Remove($timer)

        $result = $null; $errMsg = $null
        try {
            $output = $ps.EndInvoke($asyncResult)
            if ($ps.HadErrors -and $ps.Streams.Error.Count -gt 0) {
                $errMsg = $ps.Streams.Error[0].ToString()
            } elseif ($null -ne $output -and $output.Count -gt 0) {
                $result = $output[$output.Count - 1]
            }
        }
        catch { $errMsg = $_.Exception.Message }
        finally { $ps.Dispose() }

        & $OnComplete $result $errMsg $State
    }.GetNewClosure())

    $timer.Start()
}

# ==============================================================================
# 4. VISUAL ICON GRID PICKER MODAL (FLUENT WPF)
# ==============================================================================
$themeAsm = [PSDeskCreator.ThemeManager].Assembly.GetName().Name

function Show-IconPickerDialog {
    param(
        [Parameter(Mandatory)][System.Windows.Window]$OwnerWindow,
        [bool]$UseDarkMode,
        [string]$InitialIconSpec = ''
    )

    $pickerXaml = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:dc="clr-namespace:PSDeskCreator;assembly=$themeAsm"
        Title="Visual Icon Picker" Width="780" Height="560" MinWidth="660" MinHeight="440"
        WindowStartupLocation="CenterOwner" FontFamily="Segoe UI" FontSize="13" UseLayoutRounding="True" SnapsToDevicePixels="True">
    <Window.Resources>
        <dc:ThemeManager x:Key="Theme"/>
        <Style TargetType="{x:Type ScrollBar}">
            <Setter Property="Width" Value="8"/><Setter Property="MinWidth" Value="8"/><Setter Property="Background" Value="Transparent"/>
            <Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type ScrollBar}"><Grid Background="Transparent" Margin="1,2"><Track x:Name="PART_Track" IsDirectionReversed="True"><Track.Thumb><Thumb><Thumb.Template><ControlTemplate TargetType="{x:Type Thumb}"><Border Background="{Binding ScrollThumbBrush, Source={StaticResource Theme}}" CornerRadius="4"/></ControlTemplate></Thumb.Template></Thumb></Track.Thumb></Track></Grid></ControlTemplate></Setter.Value></Setter>
        </Style>
        <Style x:Key="PPrimaryBtn" TargetType="Button">
            <Setter Property="Background" Value="{Binding AccentBrush, Source={StaticResource Theme}}"/><Setter Property="Foreground" Value="{Binding AccentTextBrush, Source={StaticResource Theme}}"/><Setter Property="FontWeight" Value="SemiBold"/><Setter Property="Padding" Value="16,8"/><Setter Property="Cursor" Value="Hand"/><Setter Property="BorderThickness" Value="0"/>
            <Setter Property="Template"><Setter.Value><ControlTemplate TargetType="Button"><Border Background="{TemplateBinding Background}" CornerRadius="7" Padding="{TemplateBinding Padding}"><ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/></Border></ControlTemplate></Setter.Value></Setter>
            <Style.Triggers><Trigger Property="IsMouseOver" Value="True"><Setter Property="Background" Value="{Binding AccentHoverBrush, Source={StaticResource Theme}}"/></Trigger></Style.Triggers>
        </Style>
        <Style x:Key="PSecondaryBtn" TargetType="Button">
            <Setter Property="Background" Value="{Binding CardBrush, Source={StaticResource Theme}}"/><Setter Property="Foreground" Value="{Binding TextBrush, Source={StaticResource Theme}}"/><Setter Property="BorderBrush" Value="{Binding BorderBrush, Source={StaticResource Theme}}"/><Setter Property="BorderThickness" Value="1"/><Setter Property="Padding" Value="11,6"/><Setter Property="Cursor" Value="Hand"/>
            <Setter Property="Template"><Setter.Value><ControlTemplate TargetType="Button"><Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="7" Padding="{TemplateBinding Padding}"><ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/></Border></ControlTemplate></Setter.Value></Setter>
            <Style.Triggers><Trigger Property="IsMouseOver" Value="True"><Setter Property="Background" Value="{Binding CardHoverBrush, Source={StaticResource Theme}}"/></Trigger></Style.Triggers>
        </Style>
        <Style x:Key="PTextBox" TargetType="TextBox">
            <Setter Property="Background" Value="{Binding InputBrush, Source={StaticResource Theme}}"/><Setter Property="Foreground" Value="{Binding TextBrush, Source={StaticResource Theme}}"/><Setter Property="CaretBrush" Value="{Binding AccentBrush, Source={StaticResource Theme}}"/><Setter Property="BorderBrush" Value="{Binding BorderBrush, Source={StaticResource Theme}}"/><Setter Property="BorderThickness" Value="1"/><Setter Property="Padding" Value="10,6"/><Setter Property="VerticalContentAlignment" Value="Center"/>
            <Setter Property="Template"><Setter.Value><ControlTemplate TargetType="TextBox"><Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="7"><Grid><ScrollViewer x:Name="PART_ContentHost" Margin="2,0" VerticalAlignment="Center"/><TextBlock x:Name="Wm" Text="{TemplateBinding Tag}" Margin="10,0" Foreground="{Binding MutedBrush, Source={StaticResource Theme}}" Opacity="0.7" IsHitTestVisible="False" VerticalAlignment="Center" Visibility="Collapsed"/></Grid></Border><ControlTemplate.Triggers><Trigger Property="Text" Value=""><Setter TargetName="Wm" Property="Visibility" Value="Visible"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter>
        </Style>
    </Window.Resources>
    <Window.Background><Binding Path="BgBrush" Source="{StaticResource Theme}"/></Window.Background>
    <Window.Foreground><Binding Path="TextBrush" Source="{StaticResource Theme}"/></Window.Foreground>
    <Grid Margin="18">
        <Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="Auto"/></Grid.RowDefinitions>
        <Grid Grid.Row="0" Margin="0,0,0,10">
            <Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
            <TextBox x:Name="TxtIconFile" Grid.Column="0" Style="{StaticResource PTextBox}" Margin="0,0,8,0"/>
            <Button x:Name="BtnBrowseLib" Grid.Column="1" Content="Browse .exe / .dll / .ico..." Style="{StaticResource PSecondaryBtn}"/>
        </Grid>
        <Grid Grid.Row="1" Margin="0,0,0,12">
            <Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="155"/></Grid.ColumnDefinitions>
            <StackPanel Grid.Column="0" Orientation="Horizontal" VerticalAlignment="Center">
                <TextBlock Text="Presets:" FontSize="12" Foreground="{Binding MutedBrush, Source={StaticResource Theme}}" VerticalAlignment="Center" Margin="0,0,8,0"/>
                <Button x:Name="BtnPresetImageres" Content="imageres.dll" Style="{StaticResource PSecondaryBtn}" FontSize="11.5" Margin="0,0,6,0"/>
                <Button x:Name="BtnPresetShell32" Content="shell32.dll" Style="{StaticResource PSecondaryBtn}" FontSize="11.5" Margin="0,0,6,0"/>
                <Button x:Name="BtnPresetDdores" Content="ddores.dll" Style="{StaticResource PSecondaryBtn}" FontSize="11.5" Margin="0,0,6,0"/>
                <Button x:Name="BtnPresetPifmgr" Content="pifmgr.dll" Style="{StaticResource PSecondaryBtn}" FontSize="11.5"/>
            </StackPanel>
            <TextBox x:Name="TxtIndexFilter" Grid.Column="1" Style="{StaticResource PTextBox}" Tag="Filter index (e.g. 15)"/>
        </Grid>
        <Border Grid.Row="2" Background="{Binding SurfaceBrush, Source={StaticResource Theme}}" BorderBrush="{Binding BorderBrush, Source={StaticResource Theme}}" BorderThickness="1" CornerRadius="10" Padding="6">
            <ListBox x:Name="LstIcons" Background="Transparent" BorderThickness="0" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
                <ListBox.ItemsPanel><ItemsPanelTemplate><WrapPanel IsItemsHost="True" Orientation="Horizontal"/></ItemsPanelTemplate></ListBox.ItemsPanel>
                <ListBox.ItemContainerStyle>
                    <Style TargetType="ListBoxItem">
                        <Setter Property="Background" Value="{Binding CardBrush, Source={StaticResource Theme}}"/><Setter Property="BorderBrush" Value="{Binding BorderBrush, Source={StaticResource Theme}}"/><Setter Property="Padding" Value="0"/><Setter Property="Margin" Value="5"/>
                        <Setter Property="Template"><Setter.Value><ControlTemplate TargetType="ListBoxItem"><Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1" CornerRadius="8" Width="78" Height="78" Cursor="Hand"><ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/></Border></ControlTemplate></Setter.Value></Setter>
                        <Style.Triggers>
                            <Trigger Property="IsMouseOver" Value="True"><Setter Property="Background" Value="{Binding CardHoverBrush, Source={StaticResource Theme}}"/></Trigger>
                            <Trigger Property="IsSelected" Value="True"><Setter Property="Background" Value="{Binding SelectedBgBrush, Source={StaticResource Theme}}"/><Setter Property="BorderBrush" Value="{Binding SelectedBdBrush, Source={StaticResource Theme}}"/></Trigger>
                        </Style.Triggers>
                    </Style>
                </ListBox.ItemContainerStyle>
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
                            <Image Source="{Binding Image}" Width="36" Height="36" RenderOptions.BitmapScalingMode="HighQuality" Margin="0,2,0,5"/>
                            <TextBlock Text="{Binding Label}" FontSize="11" Foreground="{Binding MutedBrush, Source={StaticResource Theme}}" HorizontalAlignment="Center"/>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Border>
        <Grid Grid.Row="3" Margin="0,12,0,0">
            <Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="Auto"/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
            <TextBlock x:Name="TxtPickerStatus" Grid.Column="0" Text="Select an icon tile..." FontSize="12" Foreground="{Binding MutedBrush, Source={StaticResource Theme}}" VerticalAlignment="Center"/>
            <Button x:Name="BtnPickerCancel" Grid.Column="1" Content="Cancel" Style="{StaticResource PSecondaryBtn}" Margin="0,0,8,0"/>
            <Button x:Name="BtnPickerUse" Grid.Column="2" Content="Use Selected Icon" Style="{StaticResource PPrimaryBtn}"/>
        </Grid>
    </Grid>
</Window>
"@


    [xml]$pxml = $pickerXaml
    $pickerWin = [System.Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader($pxml)))
    $pickerWin.Owner = $OwnerWindow
    $pickerWin.Resources['Theme'].Configure($UseDarkMode, $true)

    $pickerWin.Add_SourceInitialized({
        $phwnd = (New-Object System.Windows.Interop.WindowInteropHelper($pickerWin)).Handle
        if ($phwnd -ne [IntPtr]::Zero) { [PSDeskCreator.NativeMethods]::ApplyWindowChromeAttributes($phwnd, $UseDarkMode) }
    })

    $txtIconFile       = $pickerWin.FindName('TxtIconFile')
    $btnBrowseLib      = $pickerWin.FindName('BtnBrowseLib')
    $btnPresetImageres = $pickerWin.FindName('BtnPresetImageres')
    $btnPresetShell32  = $pickerWin.FindName('BtnPresetShell32')
    $btnPresetDdores   = $pickerWin.FindName('BtnPresetDdores')
    $btnPresetPifmgr   = $pickerWin.FindName('BtnPresetPifmgr')
    $txtIndexFilter    = $pickerWin.FindName('TxtIndexFilter')
    $lstIcons          = $pickerWin.FindName('LstIcons')
    $txtPickerStatus   = $pickerWin.FindName('TxtPickerStatus')
    $btnPickerCancel   = $pickerWin.FindName('BtnPickerCancel')
    $btnPickerUse      = $pickerWin.FindName('BtnPickerUse')

    $script:PickerAllTiles = @()
    $script:PickerResult   = $null

    $loadLib = {
        param([string]$LibPath, [int]$SelectIdx = 0)
        $cleanPath = [Environment]::ExpandEnvironmentVariables($LibPath.Trim().Trim('"'))
        if (-not (Test-Path -LiteralPath $cleanPath -PathType Leaf)) {
            $txtPickerStatus.Text = "File not found: $cleanPath"
            $lstIcons.ItemsSource = @()
            return
        }
        $txtIconFile.Text = $cleanPath
        $total = [PSDeskCreator.NativeMethods]::GetEmbeddedIconCount($cleanPath)
        if ($total -le 0) {
            $single = [PSDeskCreator.NativeMethods]::ExtractIndexedIcon($cleanPath, 0, 48)
            if ($single) {
                $script:PickerAllTiles = @([PSCustomObject]@{ Index = 0; Label = '#0'; Image = $single })
                $lstIcons.ItemsSource = $script:PickerAllTiles
                $lstIcons.SelectedIndex = 0
                $txtPickerStatus.Text = "Loaded icon from $(Split-Path -Path $cleanPath -Leaf)"
            }
            else {
                $txtPickerStatus.Text = 'No embedded icons found in this file.'
                $lstIcons.ItemsSource = @()
            }
            return
        }
        $limit = [Math]::Min($total, 450)
        $tiles = New-Object 'System.Collections.Generic.List[PSObject]'
        for ($i = 0; $i -lt $limit; $i++) {
            $bmp = [PSDeskCreator.NativeMethods]::ExtractIndexedIcon($cleanPath, $i, 48)
            if ($bmp) { $tiles.Add([PSCustomObject]@{ Index = $i; Label = "#$i"; Image = $bmp }) }
        }
        $script:PickerAllTiles = @($tiles)
        $lstIcons.ItemsSource = $script:PickerAllTiles
        $txtPickerStatus.Text = "Loaded $($script:PickerAllTiles.Count) of $total icons from $(Split-Path -Path $cleanPath -Leaf)"
        $match = $script:PickerAllTiles | Where-Object { $_.Index -eq $SelectIdx } | Select-Object -First 1
        if ($match) { $lstIcons.SelectedItem = $match; $lstIcons.ScrollIntoView($match) }
    }

    $txtIndexFilter.Add_TextChanged({
        $q = $txtIndexFilter.Text.Trim()
        if ([string]::IsNullOrWhiteSpace($q)) { $lstIcons.ItemsSource = $script:PickerAllTiles }
        else { $lstIcons.ItemsSource = @($script:PickerAllTiles | Where-Object { $_.Label -like "*$q*" }) }
    })

    $btnPresetImageres.Add_Click({ & $loadLib "$env:WINDIR\System32\imageres.dll" 0 })
    $btnPresetShell32.Add_Click({ & $loadLib "$env:WINDIR\System32\shell32.dll" 0 })
    $btnPresetDdores.Add_Click({ & $loadLib "$env:WINDIR\System32\ddores.dll" 0 })
    $btnPresetPifmgr.Add_Click({ & $loadLib "$env:WINDIR\System32\pifmgr.dll" 0 })

    $btnBrowseLib.Add_Click({
        $dlg = New-Object Microsoft.Win32.OpenFileDialog
        $dlg.Title = 'Select Icon Library or Executable'
        $dlg.Filter = 'Icon Sources (*.dll;*.exe;*.ico)|*.dll;*.exe;*.ico|All Files (*.*)|*.*'
        if ($dlg.ShowDialog($pickerWin) -eq $true) { & $loadLib $dlg.FileName 0 }
    })

    $lstIcons.Add_SelectionChanged({
        $sel = $lstIcons.SelectedItem
        if ($sel) { $txtPickerStatus.Text = "Selected: $($txtIconFile.Text),$($sel.Index)" }
    })
    $lstIcons.Add_MouseDoubleClick({
        $sel = $lstIcons.SelectedItem
        if ($sel) { $script:PickerResult = "$($txtIconFile.Text),$($sel.Index)"; $pickerWin.DialogResult = $true; $pickerWin.Close() }
    })
    $btnPickerUse.Add_Click({
        $sel = $lstIcons.SelectedItem
        if ($sel) { $script:PickerResult = "$($txtIconFile.Text),$($sel.Index)"; $pickerWin.DialogResult = $true; $pickerWin.Close() }
    })
    $btnPickerCancel.Add_Click({ $pickerWin.DialogResult = $false; $pickerWin.Close() })

    $startLib = "$env:WINDIR\System32\shell32.dll"; $startIdx = 0
    if (-not [string]::IsNullOrWhiteSpace($InitialIconSpec)) {
        $parts = $InitialIconSpec -split ','
        $cand = [Environment]::ExpandEnvironmentVariables($parts[0].Trim().Trim('"'))
        if (Test-Path -LiteralPath $cand -PathType Leaf) {
            $startLib = $cand
            if ($parts.Count -gt 1 -and ($parts[1].Trim() -match '^\d+$')) { $startIdx = [int]$parts[1].Trim() }
        }
    }
    & $loadLib $startLib $startIdx
    [void]$pickerWin.ShowDialog()
    return $script:PickerResult
}

# ==============================================================================
# 5. MAIN FLUENT WPF WINDOW XAML (MATCHING SHORTCUT STUDIO ARCHITECTURE)
# ==============================================================================
$mainXaml = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:dc="clr-namespace:PSDeskCreator;assembly=$themeAsm"
        Title="PowerShell Desktop Shortcut Creator (Administrator)"
        Width="700" Height="680" MinWidth="540" MinHeight="480"
        WindowStartupLocation="CenterScreen"
        FontFamily="Segoe UI" FontSize="13"
        AllowDrop="True" UseLayoutRounding="True" SnapsToDevicePixels="True">
 
    <Window.Resources>
        <dc:ThemeManager x:Key="Theme"/>
 
        <Style TargetType="{x:Type ScrollBar}">
            <Setter Property="Width" Value="8"/><Setter Property="MinWidth" Value="8"/><Setter Property="Background" Value="Transparent"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ScrollBar}">
                        <Grid Background="Transparent" Margin="1,2">
                            <Track x:Name="PART_Track" IsDirectionReversed="True">
                                <Track.Thumb>
                                    <Thumb>
                                        <Thumb.Template>
                                            <ControlTemplate TargetType="{x:Type Thumb}">
                                                <Border Background="{Binding ScrollThumbBrush, Source={StaticResource Theme}}" CornerRadius="4"/>
                                            </ControlTemplate>
                                        </Thumb.Template>
                                    </Thumb>
                                </Track.Thumb>
                            </Track>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
 
        <Style x:Key="PrimaryButton" TargetType="Button">
            <Setter Property="Background" Value="{Binding AccentBrush, Source={StaticResource Theme}}"/>
            <Setter Property="Foreground" Value="{Binding AccentTextBrush, Source={StaticResource Theme}}"/>
            <Setter Property="FontWeight" Value="SemiBold"/>
            <Setter Property="Padding" Value="18,8"/>
            <Setter Property="MinHeight" Value="34"/>
            <Setter Property="Cursor" Value="Hand"/>
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border x:Name="Bd" Background="{TemplateBinding Background}" CornerRadius="7" Padding="{TemplateBinding Padding}">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsEnabled" Value="False">
                                <Setter TargetName="Bd" Property="Opacity" Value="0.45"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Background" Value="{Binding AccentHoverBrush, Source={StaticResource Theme}}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
 
        <Style x:Key="SecondaryButton" TargetType="Button">
            <Setter Property="Background" Value="{Binding CardBrush, Source={StaticResource Theme}}"/>
            <Setter Property="Foreground" Value="{Binding TextBrush, Source={StaticResource Theme}}"/>
            <Setter Property="BorderBrush" Value="{Binding BorderBrush, Source={StaticResource Theme}}"/>
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="Padding" Value="12,6"/>
            <Setter Property="MinHeight" Value="32"/>
            <Setter Property="Cursor" Value="Hand"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border x:Name="Bd" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="7" Padding="{TemplateBinding Padding}">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsEnabled" Value="False">
                                <Setter TargetName="Bd" Property="Opacity" Value="0.45"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Background" Value="{Binding CardHoverBrush, Source={StaticResource Theme}}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
 
        <Style x:Key="PillRadio" TargetType="RadioButton">
            <Setter Property="Foreground" Value="{Binding MutedBrush, Source={StaticResource Theme}}"/>
            <Setter Property="Background" Value="Transparent"/>
            <Setter Property="FontSize" Value="11.5"/>
            <Setter Property="FontWeight" Value="SemiBold"/>
            <Setter Property="Padding" Value="10,5"/>
            <Setter Property="Cursor" Value="Hand"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="RadioButton">
                        <Border Background="{TemplateBinding Background}" CornerRadius="5" Padding="{TemplateBinding Padding}">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter Property="Background" Value="{Binding AccentBrush, Source={StaticResource Theme}}"/>
                    <Setter Property="Foreground" Value="{Binding AccentTextBrush, Source={StaticResource Theme}}"/>
                </Trigger>
                <MultiTrigger>
                    <MultiTrigger.Conditions>
                        <Condition Property="IsMouseOver" Value="True"/>
                        <Condition Property="IsChecked" Value="False"/>
                    </MultiTrigger.Conditions>
                    <Setter Property="Background" Value="{Binding CardHoverBrush, Source={StaticResource Theme}}"/>
                    <Setter Property="Foreground" Value="{Binding TextBrush, Source={StaticResource Theme}}"/>
                </MultiTrigger>
            </Style.Triggers>
        </Style>
 
        <Style x:Key="ModernTextBox" TargetType="TextBox">
            <Setter Property="Background" Value="{Binding InputBrush, Source={StaticResource Theme}}"/>
            <Setter Property="Foreground" Value="{Binding TextBrush, Source={StaticResource Theme}}"/>
            <Setter Property="CaretBrush" Value="{Binding AccentBrush, Source={StaticResource Theme}}"/>
            <Setter Property="BorderBrush" Value="{Binding BorderBrush, Source={StaticResource Theme}}"/>
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="Padding" Value="9,6"/>
            <Setter Property="MinHeight" Value="32"/>
            <Setter Property="VerticalContentAlignment" Value="Center"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="TextBox">
                        <Border x:Name="Bd" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="7">
                            <Grid>
                                <ScrollViewer x:Name="PART_ContentHost" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                                <TextBlock x:Name="Watermark" Text="{TemplateBinding Tag}" Margin="11,6,9,6" Foreground="{Binding MutedBrush, Source={StaticResource Theme}}" Opacity="0.7" IsHitTestVisible="False" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Visibility="Collapsed"/>
                            </Grid>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="Text" Value="">
                                <Setter TargetName="Watermark" Property="Visibility" Value="Visible"/>
                            </Trigger>
                            <Trigger Property="IsKeyboardFocused" Value="True">
                                <Setter TargetName="Bd" Property="BorderBrush" Value="{Binding AccentBrush, Source={StaticResource Theme}}"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
 
        <Style x:Key="ModernCheckBox" TargetType="CheckBox">
            <Setter Property="Background" Value="{Binding InputBrush, Source={StaticResource Theme}}"/>
            <Setter Property="BorderBrush" Value="{Binding BorderBrush, Source={StaticResource Theme}}"/>
            <Setter Property="Foreground" Value="{Binding TextBrush, Source={StaticResource Theme}}"/>
            <Setter Property="Cursor" Value="Hand"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="CheckBox">
                        <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
                            <Border Width="18" Height="18" CornerRadius="5" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1">
                                <TextBlock x:Name="CheckGlyph" Text="&#xE73E;" FontFamily="Segoe Fluent Icons, Segoe MDL2 Assets" FontSize="11" Foreground="{Binding AccentTextBrush, Source={StaticResource Theme}}" HorizontalAlignment="Center" VerticalAlignment="Center" Visibility="Collapsed"/>
                            </Border>
                            <ContentPresenter Margin="9,0,0,0" VerticalAlignment="Center"/>
                        </StackPanel>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsChecked" Value="True">
                                <Setter TargetName="CheckGlyph" Property="Visibility" Value="Visible"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter Property="Background" Value="{Binding AccentBrush, Source={StaticResource Theme}}"/>
                    <Setter Property="BorderBrush" Value="{Binding AccentBrush, Source={StaticResource Theme}}"/>
                </Trigger>
                <Trigger Property="IsEnabled" Value="False">
                    <Setter Property="Opacity" Value="0.45"/>
                </Trigger>
            </Style.Triggers>
        </Style>
 
        <Style x:Key="ModernComboBox" TargetType="ComboBox">
            <Setter Property="Background" Value="{Binding InputBrush, Source={StaticResource Theme}}"/>
            <Setter Property="Foreground" Value="{Binding TextBrush, Source={StaticResource Theme}}"/>
            <Setter Property="BorderBrush" Value="{Binding BorderBrush, Source={StaticResource Theme}}"/>
            <Setter Property="MinHeight" Value="32"/>
            <Setter Property="Cursor" Value="Hand"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ComboBox">
                        <Grid>
                            <ToggleButton Focusable="False" IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" ClickMode="Press">
                                <ToggleButton.Template>
                                    <ControlTemplate TargetType="ToggleButton">
                                        <Border Background="{Binding InputBrush, Source={StaticResource Theme}}" BorderBrush="{Binding BorderBrush, Source={StaticResource Theme}}" BorderThickness="1" CornerRadius="7">
                                            <TextBlock Text="&#xE70D;" FontFamily="Segoe Fluent Icons, Segoe MDL2 Assets" FontSize="11" Foreground="{Binding MutedBrush, Source={StaticResource Theme}}" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,10,0"/>
                                        </Border>
                                    </ControlTemplate>
                                </ToggleButton.Template>
                            </ToggleButton>
                            <ContentPresenter IsHitTestVisible="False" Content="{TemplateBinding SelectionBoxItem}" ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}" Margin="10,0,26,0" VerticalAlignment="Center" HorizontalAlignment="Left"/>
                            <Popup Placement="Bottom" IsOpen="{TemplateBinding IsDropDownOpen}" AllowsTransparency="True" Focusable="False" PopupAnimation="Fade">
                                <Border Background="{Binding CardBrush, Source={StaticResource Theme}}" BorderBrush="{Binding BorderBrush, Source={StaticResource Theme}}" BorderThickness="1" CornerRadius="7" Margin="0,4,0,0" MinWidth="{TemplateBinding ActualWidth}">
                                    <ScrollViewer MaxHeight="200">
                                        <ItemsPresenter/>
                                    </ScrollViewer>
                                </Border>
                            </Popup>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsEnabled" Value="False">
                                <Setter Property="Opacity" Value="0.45"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
 
        <Style TargetType="ComboBoxItem">
            <Setter Property="Padding" Value="10,7"/>
            <Setter Property="Foreground" Value="{Binding TextBrush, Source={StaticResource Theme}}"/>
            <Setter Property="Background" Value="Transparent"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ComboBoxItem">
                        <Border x:Name="Bd" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" CornerRadius="5" Margin="3,2">
                            <ContentPresenter/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsHighlighted" Value="True">
                    <Setter Property="Background" Value="{Binding CardHoverBrush, Source={StaticResource Theme}}"/>
                </Trigger>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="Background" Value="{Binding SelectedBgBrush, Source={StaticResource Theme}}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
 
    <Window.Background>
        <Binding Path="BgBrush" Source="{StaticResource Theme}"/>
    </Window.Background>
    <Window.Foreground>
        <Binding Path="TextBrush" Source="{StaticResource Theme}"/>
    </Window.Foreground>
 
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
 
        <!-- TOP FLUENT HEADER BAR -->
        <Border Grid.Row="0" Background="{Binding SurfaceBrush, Source={StaticResource Theme}}" BorderBrush="{Binding BorderBrush, Source={StaticResource Theme}}" BorderThickness="0,0,0,1" Padding="20,13">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="Auto"/>
                </Grid.ColumnDefinitions>
 
                <Grid Grid.Column="0" VerticalAlignment="Center" Margin="0,0,14,0">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <Border Grid.Column="0" Width="38" Height="38" CornerRadius="9" Background="{Binding AccentBrush, Source={StaticResource Theme}}" Margin="0,0,12,0">
                        <TextBlock Text="&#xE71B;" FontFamily="Segoe Fluent Icons, Segoe MDL2 Assets" FontSize="18" Foreground="{Binding AccentTextBrush, Source={StaticResource Theme}}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    </Border>
                    <StackPanel Grid.Column="1" VerticalAlignment="Center">
                        <TextBlock Text="PowerShell Desktop Shortcut Creator" FontSize="16.5" FontWeight="SemiBold" Foreground="{Binding TextBrush, Source={StaticResource Theme}}"/>
                        <TextBlock Text="Browse or drop a .ps1 file, pick an icon, and configure how PowerShell runs it." FontSize="12" Foreground="{Binding MutedBrush, Source={StaticResource Theme}}" TextTrimming="CharacterEllipsis"/>
                    </StackPanel>
                </Grid>
 
                <StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center">
                    <Border Background="{Binding ElevationBgBrush, Source={StaticResource Theme}}" CornerRadius="6" Padding="9,5" Margin="0,0,8,0" VerticalAlignment="Center">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="&#xEA18;" FontFamily="Segoe Fluent Icons, Segoe MDL2 Assets" FontSize="12" Foreground="{Binding ElevationFgBrush, Source={StaticResource Theme}}" VerticalAlignment="Center" Margin="0,0,5,0"/>
                            <TextBlock Text="Admin" FontSize="11.5" FontWeight="SemiBold" Foreground="{Binding ElevationFgBrush, Source={StaticResource Theme}}" VerticalAlignment="Center"/>
                        </StackPanel>
                    </Border>
 
                    <Border Background="{Binding InputBrush, Source={StaticResource Theme}}" BorderBrush="{Binding BorderBrush, Source={StaticResource Theme}}" BorderThickness="1" CornerRadius="7" Padding="3">
                        <StackPanel Orientation="Horizontal">
                            <RadioButton x:Name="rbThemeAuto" Content="Auto" Style="{StaticResource PillRadio}" GroupName="ThemeGroup" IsChecked="True"/>
                            <RadioButton x:Name="rbThemeDark" Content="Dark" Style="{StaticResource PillRadio}" GroupName="ThemeGroup" Margin="2,0"/>
                            <RadioButton x:Name="rbThemeLight" Content="Light" Style="{StaticResource PillRadio}" GroupName="ThemeGroup"/>
                        </StackPanel>
                    </Border>
                </StackPanel>
            </Grid>
        </Border>
 
        <!-- SCROLLABLE MIDDLE BODY -->
        <ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto" Padding="20,14,16,8">
            <StackPanel>
                <TextBlock Text="PowerShell Script (.ps1):" FontWeight="SemiBold" Margin="0,0,0,5"/>
                <Grid Margin="0,0,0,12">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="Auto"/>
                    </Grid.ColumnDefinitions>
                    <TextBox x:Name="txtScriptPath" Grid.Column="0" Style="{StaticResource ModernTextBox}" Tag="Click Browse or drop a .ps1 script..." Margin="0,0,8,0"/>
                    <Button x:Name="btnBrowse" Grid.Column="1" Content="Browse..." Style="{StaticResource SecondaryButton}" Width="92"/>
                </Grid>
 
                <TextBlock Text="Desktop Shortcut Name:" FontWeight="SemiBold" Margin="0,0,0,5"/>
                <TextBox x:Name="txtShortcutName" Style="{StaticResource ModernTextBox}" Tag="Shortcut name on Desktop" Margin="0,0,0,12"/>
 
                <TextBlock Text="Shortcut Icon (.ico, .exe, .dll):" FontWeight="SemiBold" Margin="0,0,0,5"/>
                <Grid Margin="0,0,0,14">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="Auto"/>
                    </Grid.ColumnDefinitions>
                    <Border Grid.Column="0" Width="44" Height="44" CornerRadius="8" Background="{Binding CardBrush, Source={StaticResource Theme}}" BorderBrush="{Binding BorderBrush, Source={StaticResource Theme}}" BorderThickness="1" Margin="0,0,10,0">
                        <Image x:Name="imgIcon" Width="32" Height="32" RenderOptions.BitmapScalingMode="HighQuality"/>
                    </Border>
                    <TextBox x:Name="txtIconPath" Grid.Column="1" Style="{StaticResource ModernTextBox}" VerticalAlignment="Center" Margin="0,0,8,0"/>
                    <StackPanel Grid.Column="2" Orientation="Horizontal" VerticalAlignment="Center">
                        <Button x:Name="btnPickIconGrid" Style="{StaticResource SecondaryButton}" Margin="0,0,6,0" ToolTip="Browse embedded icons visually from .dll, .exe, or .ico files">
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="&#xE8A9;" FontFamily="Segoe Fluent Icons, Segoe MDL2 Assets" FontSize="13" Foreground="{Binding AccentBrush, Source={StaticResource Theme}}" VerticalAlignment="Center" Margin="0,0,6,0"/>
                                <TextBlock Text="Pick Icon Grid..." FontWeight="SemiBold" VerticalAlignment="Center"/>
                            </StackPanel>
                        </Button>
                        <Button x:Name="btnBrowseIcon" Content="Browse..." Style="{StaticResource SecondaryButton}" Margin="0,0,6,0"/>
                        <Button x:Name="btnResetIcon" Content="Reset" Style="{StaticResource SecondaryButton}"/>
                    </StackPanel>
                </Grid>
 
                <!-- POWER SHELL LAUNCH OPTIONS CARD -->
                <Border Background="{Binding SurfaceBrush, Source={StaticResource Theme}}" BorderBrush="{Binding BorderBrush, Source={StaticResource Theme}}" BorderThickness="1" CornerRadius="10" Padding="16">
                    <StackPanel>
                        <TextBlock Text="PowerShell Launch Options" FontWeight="SemiBold" FontSize="13.5" Foreground="{Binding AccentBrush, Source={StaticResource Theme}}" Margin="0,0,0,12"/>
 
                        <WrapPanel Orientation="Horizontal" VerticalAlignment="Center" Margin="0,0,0,10">
                            <TextBlock Text="PowerShell Mode:" VerticalAlignment="Center" Margin="0,0,8,0"/>
                            <ComboBox x:Name="cmbMode" Style="{StaticResource ModernComboBox}" Width="232" Margin="0,0,12,0"/>
                            <TextBlock x:Name="lblModeStatus" Text="" VerticalAlignment="Center" FontSize="12"/>
                        </WrapPanel>
 
                        <WrapPanel Orientation="Horizontal" VerticalAlignment="Center" Margin="0,0,0,10">
                            <CheckBox x:Name="chkRunAs" Style="{StaticResource ModernCheckBox}" Content="Run as Administrator (UAC prompt on launch)" Margin="0,2,18,2"/>
                            <StackPanel Orientation="Horizontal" VerticalAlignment="Center" Margin="0,2,0,2">
                                <TextBlock Text="Window:" VerticalAlignment="Center" Margin="0,0,8,0"/>
                                <ComboBox x:Name="cmbWindow" Style="{StaticResource ModernComboBox}" Width="118"/>
                            </StackPanel>
                        </WrapPanel>
 
                        <CheckBox x:Name="chkNoExit" Style="{StaticResource ModernCheckBox}" Content="Keep PowerShell window open after script finishes (-NoExit)" Margin="0,0,0,7"/>
                        <CheckBox x:Name="chkBypass" Style="{StaticResource ModernCheckBox}" Content="Bypass Execution Policy (-ExecutionPolicy Bypass)" IsChecked="True" Margin="0,0,0,12"/>
 
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>
                            <TextBlock Grid.Column="0" Text="Script Arguments (optional):" VerticalAlignment="Center" Margin="0,0,10,0"/>
                            <TextBox x:Name="txtArgs" Grid.Column="1" Style="{StaticResource ModernTextBox}" Tag="e.g. -Verbose -Environment Prod"/>
                        </Grid>
                    </StackPanel>
                </Border>
            </StackPanel>
        </ScrollViewer>
 
        <!-- PINNED COMMAND PREVIEW BOX -->
        <StackPanel Grid.Row="2" Margin="20,4,20,10">
            <TextBlock Text="Shortcut Target Command Preview:" FontSize="12" Foreground="{Binding MutedBrush, Source={StaticResource Theme}}" Margin="0,0,0,4"/>
            <TextBox x:Name="txtPreview" Style="{StaticResource ModernTextBox}" Height="66" IsReadOnly="True" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" VerticalContentAlignment="Top" FontFamily="Consolas" FontSize="11.5" Background="{Binding PreviewBgBrush, Source={StaticResource Theme}}" Foreground="{Binding PreviewFgBrush, Source={StaticResource Theme}}"/>
        </StackPanel>
 
        <!-- BOTTOM STATUS FOOTER & ACTIONS -->
        <Border Grid.Row="3" Background="{Binding SurfaceBrush, Source={StaticResource Theme}}" BorderBrush="{Binding BorderBrush, Source={StaticResource Theme}}" BorderThickness="0,1,0,0" Padding="20,10">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="Auto"/>
                </Grid.ColumnDefinitions>
 
                <Ellipse x:Name="statusDot" Grid.Column="0" Width="8" Height="8" Fill="#9CA3AF" VerticalAlignment="Center" Margin="0,0,9,0"/>
                <TextBlock x:Name="lblStatus" Grid.Column="1" Text="Select a PowerShell script to begin." Foreground="{Binding MutedBrush, Source={StaticResource Theme}}" VerticalAlignment="Center" TextWrapping="Wrap" Margin="0,0,12,0"/>
 
                <StackPanel Grid.Column="2" Orientation="Horizontal">
                    <Button x:Name="btnCreate" Content="Create Shortcut" Style="{StaticResource PrimaryButton}" IsEnabled="False" Width="138" Margin="0,0,8,0"/>
                    <Button x:Name="btnClose" Content="Close" Style="{StaticResource SecondaryButton}" Width="82"/>
                </StackPanel>
            </Grid>
        </Border>
    </Grid>
</Window>
"@


[xml]$xmlDoc = $mainXaml
$window = [System.Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader($xmlDoc)))
$themeMgr = $window.Resources['Theme']

$rbThemeAuto     = $window.FindName('rbThemeAuto')
$rbThemeDark     = $window.FindName('rbThemeDark')
$rbThemeLight    = $window.FindName('rbThemeLight')
$txtScriptPath   = $window.FindName('txtScriptPath')
$btnBrowse       = $window.FindName('btnBrowse')
$txtShortcutName = $window.FindName('txtShortcutName')
$imgIcon         = $window.FindName('imgIcon')
$txtIconPath     = $window.FindName('txtIconPath')
$btnPickIconGrid = $window.FindName('btnPickIconGrid')
$btnBrowseIcon   = $window.FindName('btnBrowseIcon')
$btnResetIcon    = $window.FindName('btnResetIcon')
$cmbMode         = $window.FindName('cmbMode')
$lblModeStatus   = $window.FindName('lblModeStatus')
$chkRunAs        = $window.FindName('chkRunAs')
$cmbWindow       = $window.FindName('cmbWindow')
$chkNoExit       = $window.FindName('chkNoExit')
$chkBypass       = $window.FindName('chkBypass')
$txtArgs         = $window.FindName('txtArgs')
$txtPreview      = $window.FindName('txtPreview')
$statusDot       = $window.FindName('statusDot')
$lblStatus       = $window.FindName('lblStatus')
$btnCreate       = $window.FindName('btnCreate')
$btnClose        = $window.FindName('btnClose')

# ==============================================================================
# 6. INITIALIZATION, THEME ENGINE & SHORTCUT LOGIC
# ==============================================================================
$ps5ExePath  = Join-Path -Path $env:SystemRoot -ChildPath 'System32\WindowsPowerShell\v1.0\powershell.exe'
$ps5IconSpec = "$ps5ExePath,0"
$desktopPath = [Environment]::GetFolderPath('Desktop')

$script:CurrentThemeMode = $Theme
$script:StatusKind       = 'Neutral'
$script:IsInitializing   = $true

foreach ($m in @('PowerShell 5.1 (powershell.exe)', 'PowerShell 7.x (pwsh.exe)')) { [void]$cmbMode.Items.Add($m) }
$cmbMode.SelectedIndex = if (-not $isPS51 -and $null -ne (Get-Pwsh7Info)) { 1 } else { 0 }

foreach ($w in @('Normal', 'Minimized', 'Maximized', 'Hidden')) { [void]$cmbWindow.Items.Add($w) }
$cmbWindow.SelectedIndex = 0
$txtIconPath.Text = $ps5IconSpec

switch ($Theme) {
    'Dark'  { $rbThemeDark.IsChecked  = $true }
    'Light' { $rbThemeLight.IsChecked = $true }
    default { $rbThemeAuto.IsChecked  = $true }
}

$getDefaultIconForMode = {
    if ($cmbMode.SelectedIndex -eq 1) {
        $info = Get-Pwsh7Info
        if ($null -ne $info -and -not [string]::IsNullOrWhiteSpace($info.IconPath)) {
            return "$($info.IconPath),0"
        }
    }
    return $ps5IconSpec
}

$resolveIcon = {
    param([string]$Spec)
    $fallback = & $getDefaultIconForMode
    $raw   = if ([string]::IsNullOrWhiteSpace($Spec)) { $fallback } else { $Spec.Trim() }
    $file  = $raw
    $index = 0
    if ($raw -match '^(.*),\s*(-?\d+)$') {
        $file  = $Matches[1].Trim().Trim('"')
        $index = [int]$Matches[2]
    }
    else {
        $file = $raw.Trim('"')
    }
    $expanded = [Environment]::ExpandEnvironmentVariables($file)
    [PSCustomObject]@{ File = $expanded; Index = $index; Spec = "$expanded,$index" }
}

$refreshIcon = {
    $parsed = & $resolveIcon $txtIconPath.Text
    $imgIcon.Source = [PSDeskCreator.NativeMethods]::ExtractIndexedIcon($parsed.File, $parsed.Index, 32)
}

$buildArgs = {
    $parts = New-Object System.Collections.Generic.List[string]
    $parts.Add('-NoProfile')
    if ($cmbMode.SelectedIndex -eq 0) { $parts.Add('-STA') }
    if ([bool]$chkBypass.IsChecked) { $parts.Add('-ExecutionPolicy Bypass') }
    if ([string]$cmbWindow.SelectedItem -eq 'Hidden') { $parts.Add('-WindowStyle Hidden') }
    if ([bool]$chkNoExit.IsChecked) { $parts.Add('-NoExit') }
    $target = $txtScriptPath.Text.Trim()
    if (-not [string]::IsNullOrWhiteSpace($target)) { $parts.Add("-File `"$target`"") }
    if (-not [string]::IsNullOrWhiteSpace($txtArgs.Text)) { $parts.Add($txtArgs.Text.Trim()) }
    return ($parts -join ' ')
}

$refreshModeStatus = {
    if ($cmbMode.SelectedIndex -eq 0) {
        $lblModeStatus.Foreground = $themeMgr.MutedBrush
        $lblModeStatus.Text       = 'Built-in (Windows)'
    }
    else {
        $info = Get-Pwsh7Info
        if ($null -ne $info) {
            $lblModeStatus.Foreground = $themeMgr.SuccessBrush
            $lblModeStatus.Text       = 'Installed (Ready)'
        }
        else {
            $lblModeStatus.Foreground = $themeMgr.WarningBrush
            $lblModeStatus.Text       = 'Not installed'
        }
    }
}

$refreshState = {
    $path = $txtScriptPath.Text.Trim()
    $valid = (-not [string]::IsNullOrWhiteSpace($path)) -and (Test-Path -LiteralPath $path -PathType Leaf)
    $btnCreate.IsEnabled = $valid

    $previewExe = if ($cmbMode.SelectedIndex -eq 1) {
        $info = Get-Pwsh7Info
        if ($null -ne $info) { $info.ExePath } else { 'pwsh.exe' }
    }
    else {
        $ps5ExePath
    }
    $txtPreview.Text = if ($valid) { "`"$previewExe`" $(& $buildArgs)" } else { '' }
}

function Set-Status {
    param(
        [Parameter(Mandatory)][string]$Message,
        [ValidateSet('Neutral', 'Success', 'Warning', 'Error')][string]$Kind = 'Neutral'
    )
    $script:StatusKind = $Kind
    $lblStatus.Text = $Message
    $brush = switch ($Kind) {
        'Success' { $themeMgr.SuccessBrush }
        'Warning' { $themeMgr.WarningBrush }
        'Error'   { $themeMgr.ErrorBrush }
        default   { $themeMgr.MutedBrush }
    }
    $lblStatus.Foreground = $brush
    $statusDot.Fill       = $brush
}

function Apply-ActiveTheme {
    $useDark = Resolve-UseDarkMode -Mode $script:CurrentThemeMode
    $themeMgr.Configure($useDark, $isAdmin)
    $hwnd = (New-Object System.Windows.Interop.WindowInteropHelper($window)).Handle
    if ($hwnd -ne [IntPtr]::Zero) {
        [PSDeskCreator.NativeMethods]::ApplyWindowChromeAttributes($hwnd, $useDark)
    }
    & $refreshModeStatus
    Set-Status -Message $lblStatus.Text -Kind $script:StatusKind
}

$writeShortcutFile = {
    param(
        [string]$TargetExePath,
        [string]$ShortcutFilePath,
        [string]$ScriptFilePath,
        [string]$IconSpec,
        [string]$ModeLabel
    )

    $wsh = New-Object -ComObject WScript.Shell
    $lnk = $null
    try {
        $lnk = $wsh.CreateShortcut($ShortcutFilePath)
        $lnk.TargetPath       = $TargetExePath
        $lnk.Arguments        = (& $buildArgs)
        $lnk.WorkingDirectory = Split-Path -Path $ScriptFilePath -Parent
        $lnk.IconLocation     = $IconSpec
        $lnk.WindowStyle      = switch ([string]$cmbWindow.SelectedItem) {
            'Normal'    { 1 }
            'Minimized' { 7 }
            'Maximized' { 3 }
            'Hidden'    { 7 }
            default     { 1 }
        }
        $lnk.Description = "Run $(Split-Path -Path $ScriptFilePath -Leaf) via $ModeLabel"
        $lnk.Save()
    }
    finally {
        if ($null -ne $lnk) { [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($lnk) }
        if ($null -ne $wsh) { [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($wsh) }
    }

    if ([bool]$chkRunAs.IsChecked) {
        $bytes = [System.IO.File]::ReadAllBytes($ShortcutFilePath)
        $bytes[21] = $bytes[21] -bor 0x20
        [System.IO.File]::WriteAllBytes($ShortcutFilePath, $bytes)
    }
}

$startPwsh7Install = {
    param(
        [bool]$CreateAfterInstall,
        [string]$ShortcutPath,
        [string]$ScriptPath,
        [string]$CleanName,
        [string]$IconSpec
    )

    $btnCreate.IsEnabled = $false
    $btnClose.IsEnabled  = $false
    $btnBrowse.IsEnabled = $false
    $cmbMode.IsEnabled   = $false
    Set-Status -Message 'Installing PowerShell 7.x... Please wait.' -Kind 'Warning'

    $installWork = {
        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

        $wingetCmd = Get-Command -Name 'winget.exe' -ErrorAction SilentlyContinue
        if ($null -ne $wingetCmd) {
            $wgArgs = 'install --id Microsoft.PowerShell --exact --source winget --accept-package-agreements --accept-source-agreements --silent'
            $proc = Start-Process -FilePath $wingetCmd.Source -ArgumentList $wgArgs -Wait -PassThru -WindowStyle Hidden
            if ($proc.ExitCode -eq 0) { return 'winget' }
        }

        $arch    = if ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64') { 'win-arm64.msi' } else { 'win-x64.msi' }
        $headers = @{ 'User-Agent' = 'PowerShell-Desktop-Shortcut-Creator' }
        $release = Invoke-RestMethod -Uri 'https://api.github.com/repos/PowerShell/PowerShell/releases/latest' -Headers $headers -TimeoutSec 25 -ErrorAction Stop
        $asset   = $release.assets | Where-Object { $_.name -like "*$arch" } | Select-Object -First 1
        if ($null -eq $asset) { throw "No matching PowerShell 7 installer ($arch) was found on GitHub." }

        $msiPath = Join-Path -Path $env:TEMP -ChildPath $asset.name
        Invoke-WebRequest -Uri $asset.browser_download_url -OutFile $msiPath -UseBasicParsing -TimeoutSec 120 -ErrorAction Stop

        $msiArgs = "/i `"$msiPath`" /passive ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL=1 ADD_FILE_CONTEXT_MENU_RUNPOWERSHELL=1 USE_MU=1 ENABLE_MU=1"
        $msiProc = Start-Process -FilePath 'msiexec.exe' -ArgumentList $msiArgs -Wait -PassThru
        Remove-Item -LiteralPath $msiPath -Force -ErrorAction SilentlyContinue

        if ($msiProc.ExitCode -ne 0 -and $msiProc.ExitCode -ne 3010) {
            throw "PowerShell 7 installer exited with code $($msiProc.ExitCode)."
        }
        return 'msi'
    }

    $state = @{
        CreateAfterInstall = $CreateAfterInstall
        ShortcutPath       = $ShortcutPath
        ScriptPath         = $ScriptPath
        CleanName          = $CleanName
        IconSpec           = $IconSpec
    }

    Invoke-AsyncTask -Work $installWork -State $state -OnComplete {
        param($res, $err, $st)
        if (-not $window.IsLoaded) { return }

        $btnClose.IsEnabled  = $true
        $btnBrowse.IsEnabled = $true
        $cmbMode.IsEnabled   = $true
        & $refreshState

        if ($err) {
            & $refreshModeStatus
            Set-Status -Message "Install failed: $err" -Kind 'Error'
            [void][System.Windows.MessageBox]::Show($window, "PowerShell 7 installation failed:`n$err", 'Installation Error', 'OK', 'Error')
            return
        }

        $installedInfo = Get-Pwsh7Info
        if ($null -eq $installedInfo) {
            & $refreshModeStatus
            Set-Status -Message 'PowerShell 7 installed, but pwsh.exe was not found.' -Kind 'Error'
            [void][System.Windows.MessageBox]::Show($window, 'PowerShell 7 finished installing, but pwsh.exe could not be located automatically. Click Create Shortcut again to retry.', 'Detection Needed', 'OK', 'Warning')
            return
        }

        $finalIconSpec = $st.IconSpec
        if ([string]::IsNullOrWhiteSpace($finalIconSpec) -or ($finalIconSpec -ieq $ps5IconSpec)) {
            $finalIconSpec = "$($installedInfo.IconPath),0"
            $txtIconPath.Text = $finalIconSpec
        }

        & $refreshModeStatus
        & $refreshState

        if ($st.CreateAfterInstall) {
            try {
                & $writeShortcutFile $installedInfo.ExePath $st.ShortcutPath $st.ScriptPath $finalIconSpec 'PowerShell 7.x'
                Set-Status -Message "Installed PowerShell 7.x and created '$($st.CleanName).lnk'." -Kind 'Success'
            }
            catch {
                Set-Status -Message "Installed PS 7, but shortcut failed: $($_.Exception.Message)" -Kind 'Error'
            }
        }
        else {
            Set-Status -Message 'PowerShell 7.x installed. Ready to create shortcut.' -Kind 'Success'
        }
    }
}

# ==============================================================================
# 7. EVENT HANDLERS
# ==============================================================================
$rbThemeAuto.Add_Checked({  if (-not $script:IsInitializing) { $script:CurrentThemeMode = 'Auto';  Apply-ActiveTheme } })
$rbThemeDark.Add_Checked({  if (-not $script:IsInitializing) { $script:CurrentThemeMode = 'Dark';  Apply-ActiveTheme } })
$rbThemeLight.Add_Checked({ if (-not $script:IsInitializing) { $script:CurrentThemeMode = 'Light'; Apply-ActiveTheme } })

$prefHandler = [Microsoft.Win32.UserPreferenceChangedEventHandler]{
    param($s, $e)
    if ($script:CurrentThemeMode -eq 'Auto' -and $window.IsLoaded) {
        $window.Dispatcher.Invoke([Action]{ Apply-ActiveTheme })
    }
}
[Microsoft.Win32.SystemEvents]::add_UserPreferenceChanged($prefHandler)

$cmbMode.Add_SelectionChanged({
    if ($script:IsInitializing) { return }
    $isPs7   = ($cmbMode.SelectedIndex -eq 1)
    $curIcon = $txtIconPath.Text.Trim()

    if ($isPs7) {
        $info = Get-Pwsh7Info
        if ($null -ne $info) {
            if ([string]::IsNullOrWhiteSpace($curIcon) -or ($curIcon -ieq $ps5IconSpec)) {
                $txtIconPath.Text = "$($info.IconPath),0"
            }
        }
        else {
            & $refreshModeStatus
            & $refreshState
            $askNow = [System.Windows.MessageBox]::Show(
                $window,
                "PowerShell 7.x (pwsh.exe) is not currently installed on this PC.`n`nWould you like to download and install PowerShell 7 now?",
                'PowerShell 7.x Not Installed',
                'YesNo',
                'Question'
            )
            if ($askNow -eq 'Yes') {
                & $startPwsh7Install $false '' '' '' $txtIconPath.Text
            }
            return
        }
    }
    elseif ([string]::IsNullOrWhiteSpace($curIcon) -or ($curIcon -match '\\pwsh\.exe,0$')) {
        $txtIconPath.Text = $ps5IconSpec
    }

    & $refreshModeStatus
    & $refreshState
})

$btnBrowse.Add_Click({
    $initDir = $desktopPath
    $currentText = $txtScriptPath.Text.Trim()
    if (-not [string]::IsNullOrWhiteSpace($currentText)) {
        if (Test-Path -LiteralPath $currentText -PathType Container) { $initDir = $currentText }
        elseif (Test-Path -LiteralPath $currentText -PathType Leaf) { $initDir = Split-Path -Path $currentText -Parent }
    }

    $dlg = New-Object Microsoft.Win32.OpenFileDialog
    $dlg.Title            = 'Select a PowerShell Script (.ps1)'
    $dlg.Filter           = 'PowerShell Scripts (*.ps1)|*.ps1|All Files (*.*)|*.*'
    $dlg.InitialDirectory = $initDir
    $dlg.CheckFileExists  = $true
    $dlg.Multiselect      = $false

    if ($dlg.ShowDialog($window) -eq $true) {
        $txtScriptPath.Text   = $dlg.FileName
        $txtShortcutName.Text = [System.IO.Path]::GetFileNameWithoutExtension($dlg.FileName)
        Set-Status -Message 'Ready to create Desktop shortcut.' -Kind 'Neutral'
        & $refreshState
    }
})

$btnPickIconGrid.Add_Click({
    $useDark = Resolve-UseDarkMode -Mode $script:CurrentThemeMode
    $picked  = Show-IconPickerDialog -OwnerWindow $window -UseDarkMode $useDark -InitialIconSpec $txtIconPath.Text.Trim()
    if ($picked) {
        $txtIconPath.Text = $picked
    }
})

$btnBrowseIcon.Add_Click({
    $parsed   = & $resolveIcon $txtIconPath.Text
    $pwshInfo = if ($cmbMode.SelectedIndex -eq 1) { Get-Pwsh7Info } else { $null }
    $fallback = if ($null -ne $pwshInfo) { $pwshInfo.IconPath } else { $ps5ExePath }
    $initFile = if (Test-Path -LiteralPath $parsed.File) { $parsed.File } else { $fallback }

    $dlg = New-Object Microsoft.Win32.OpenFileDialog
    $dlg.Title            = 'Select Icon Source (.ico, .exe, .dll)'
    $dlg.Filter           = 'Icon Sources (*.ico;*.exe;*.dll)|*.ico;*.exe;*.dll|All Files (*.*)|*.*'
    $dlg.InitialDirectory = Split-Path -Path $initFile -Parent
    $dlg.CheckFileExists  = $true
    if ($dlg.ShowDialog($window) -eq $true) {
        $txtIconPath.Text = "$($dlg.FileName),0"
    }
})

$btnResetIcon.Add_Click({ $txtIconPath.Text = (& $getDefaultIconForMode) })
$txtIconPath.Add_TextChanged({ & $refreshIcon })
$txtScriptPath.Add_TextChanged({ & $refreshState })
$chkBypass.Add_Click({ & $refreshState })
$chkNoExit.Add_Click({ & $refreshState })
$txtArgs.Add_TextChanged({ & $refreshState })

$cmbWindow.Add_SelectionChanged({
    if ([string]$cmbWindow.SelectedItem -eq 'Hidden') {
        $chkNoExit.IsChecked = $false
        $chkNoExit.IsEnabled = $false
    }
    else {
        $chkNoExit.IsEnabled = $true
    }
    & $refreshState
})

$btnCreate.Add_Click({
    try {
        $scriptPath = $txtScriptPath.Text.Trim()
        if (-not (Test-Path -LiteralPath $scriptPath -PathType Leaf)) {
            Set-Status -Message 'Error: The selected script file does not exist.' -Kind 'Error'
            return
        }
        $iconInfo = & $resolveIcon $txtIconPath.Text
        if (-not (Test-Path -LiteralPath $iconInfo.File)) {
            Set-Status -Message 'Error: The selected icon file does not exist.' -Kind 'Error'
            return
        }

        $rawName = if ([string]::IsNullOrWhiteSpace($txtShortcutName.Text)) {
            [System.IO.Path]::GetFileNameWithoutExtension($scriptPath)
        } else {
            $txtShortcutName.Text.Trim()
        }
        $invalidRegex = [Regex]::Escape(([System.IO.Path]::GetInvalidFileNameChars() -join ''))
        $cleanName = ($rawName -replace "[$invalidRegex]", '').Trim()
        if ([string]::IsNullOrWhiteSpace($cleanName)) {
            $cleanName = [System.IO.Path]::GetFileNameWithoutExtension($scriptPath)
        }
        $txtShortcutName.Text = $cleanName

        $shortcutPath = Join-Path -Path $desktopPath -ChildPath "$cleanName.lnk"
        if (Test-Path -LiteralPath $shortcutPath) {
            $ow = [System.Windows.MessageBox]::Show($window, "Overwrite existing '$cleanName.lnk' on Desktop?", 'Confirm Overwrite', 'YesNo', 'Question')
            if ($ow -ne 'Yes') { return }
        }

        if ($cmbMode.SelectedIndex -eq 0) {
            & $writeShortcutFile $ps5ExePath $shortcutPath $scriptPath $iconInfo.Spec 'PowerShell 5.1'
            Set-Status -Message "Created '$cleanName.lnk' (PowerShell 5.1) on your Desktop." -Kind 'Success'
            return
        }

        $pwsh7Info = Get-Pwsh7Info
        if ($null -ne $pwsh7Info) {
            & $writeShortcutFile $pwsh7Info.ExePath $shortcutPath $scriptPath $iconInfo.Spec 'PowerShell 7.x'
            Set-Status -Message "Created '$cleanName.lnk' (PowerShell 7.x) on your Desktop." -Kind 'Success'
            return
        }

        $ask = [System.Windows.MessageBox]::Show(
            $window,
            "PowerShell 7.x (pwsh.exe) is not currently installed on this PC.`n`nWould you like to download and install PowerShell 7 now, and then create '$cleanName.lnk'?",
            'PowerShell 7.x Not Installed',
            'YesNo',
            'Question'
        )
        if ($ask -ne 'Yes') {
            Set-Status -Message 'Canceled: PowerShell 7.x is not installed.' -Kind 'Neutral'
            return
        }

        & $startPwsh7Install $true $shortcutPath $scriptPath $cleanName $iconInfo.Spec
    }
    catch {
        Set-Status -Message "Failed: $($_.Exception.Message)" -Kind 'Error'
    }
})

# Drag-and-Drop .ps1 or .ico Support Anywhere on the Window
$window.Add_DragOver({
    param($s, $e)
    if ($e.Data.GetDataPresent([System.Windows.DataFormats]::FileDrop)) {
        $e.Effects = [System.Windows.DragDropEffects]::Copy
    }
    else {
        $e.Effects = [System.Windows.DragDropEffects]::None
    }
    $e.Handled = $true
})

$window.Add_Drop({
    param($s, $e)
    if ($e.Data.GetDataPresent([System.Windows.DataFormats]::FileDrop)) {
        $files = $e.Data.GetData([System.Windows.DataFormats]::FileDrop)
        if ($files -and $files.Count -gt 0) {
            $dropped = $files[0]
            if ($dropped -match '\.(ico|exe|dll)$') {
                $txtIconPath.Text = "$dropped,0"
                Set-Status -Message "Loaded icon source: $dropped" -Kind 'Neutral'
            }
            else {
                $txtScriptPath.Text   = $dropped
                $txtShortcutName.Text = [System.IO.Path]::GetFileNameWithoutExtension($dropped)
                Set-Status -Message "Loaded script: $dropped" -Kind 'Neutral'
                & $refreshState
            }
        }
    }
})

$btnClose.Add_Click({ $window.Close() })

if ($cmbMode.SelectedIndex -eq 1) {
    $initialInfo = Get-Pwsh7Info
    if ($null -ne $initialInfo) { $txtIconPath.Text = "$($initialInfo.IconPath),0" }
}

$script:IsInitializing = $false
Apply-ActiveTheme
& $refreshIcon
& $refreshState

$window.Add_SourceInitialized({
    Apply-ActiveTheme
    [PSDeskCreator.NativeMethods]::HideConsoleWindow()
    $wa = [System.Windows.SystemParameters]::WorkArea
    $maxW = [Math]::Max(460, $wa.Width - 20)
    $maxH = [Math]::Max(400, $wa.Height - 20)
    $window.MinWidth  = [Math]::Min($window.MinWidth, $maxW)
    $window.MinHeight = [Math]::Min($window.MinHeight, $maxH)
    if ($window.Width -gt $maxW)  { $window.Width  = $maxW }
    if ($window.Height -gt $maxH) { $window.Height = $maxH }
})

$window.Add_ContentRendered({
    $window.Activate() | Out-Null
})

$window.Add_Closed({
    [Microsoft.Win32.SystemEvents]::remove_UserPreferenceChanged($prefHandler)
    foreach ($t in @($script:ActiveTimers)) {
        try { $t.Stop() } catch { }
    }
    $script:ActiveTimers.Clear()
})

[void]$window.ShowDialog()