function Initialize-RBWindowsUI {
    Add-Type -AssemblyName System.Windows.Forms
    Add-Type -AssemblyName System.Drawing
    if (-not ('RansomBackup.NativeMethods' -as [type])) {
        Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
namespace RansomBackup {
    public static class NativeMethods {
        [DllImport("user32.dll")]
        public static extern bool SetProcessDpiAwarenessContext(IntPtr value);
        [DllImport("user32.dll")]
        public static extern bool SetProcessDPIAware();
    }
}
'@
    }
    try {
        [void][RansomBackup.NativeMethods]::SetProcessDpiAwarenessContext([IntPtr](-4))
    } catch {
        try { [void][RansomBackup.NativeMethods]::SetProcessDPIAware() } catch { }
    }
    [Windows.Forms.Application]::EnableVisualStyles()
}

function Set-RBPrimaryButton {
    param([Parameter(Mandatory=$true)]$Button)
    $Button.FlatStyle = 'Flat'
    $Button.FlatAppearance.BorderSize = 0
    $Button.BackColor = [Drawing.Color]::FromArgb(164, 239, 111)
    $Button.ForeColor = [Drawing.Color]::FromArgb(15, 33, 24)
    $Button.Cursor = [Windows.Forms.Cursors]::Hand
}

function Set-RBSecondaryButton {
    param([Parameter(Mandatory=$true)]$Button)
    $Button.FlatStyle = 'Flat'
    $Button.FlatAppearance.BorderColor = [Drawing.Color]::FromArgb(45, 82, 63)
    $Button.BackColor = [Drawing.Color]::White
    $Button.ForeColor = [Drawing.Color]::FromArgb(20, 45, 33)
    $Button.Cursor = [Windows.Forms.Cursors]::Hand
}

function Save-RBRecoveryKeyFile {
    param([Parameter(Mandatory=$true)][string]$RecoveryKey, [string]$Email = '', [ValidateSet('it','en')][string]$Language = 'it')
    $dialog = New-Object Windows.Forms.SaveFileDialog
    $dialog.Title = if($Language -eq 'en'){'Save the recovery key'}else{'Salva la chiave di recupero'}
    $dialog.FileName = if($Language -eq 'en'){'RansomBackup-Recovery-Key.txt'}else{'RansomBackup-Chiave-di-recupero.txt'}
    $dialog.Filter = if($Language -eq 'en'){'Text document (*.txt)|*.txt'}else{'Documento di testo (*.txt)|*.txt'}
    if ($dialog.ShowDialog() -ne 'OK') { return $false }
    $content = if($Language -eq 'en'){@(
        'RANSOMBACKUP FREE - RECOVERY KEY';'';$RecoveryKey;'';"Account: $Email";"Saved: $(Get-Date -Format 'yyyy-MM-dd HH:mm')";''
        'RansomBackup does not store this key.';'Without this key, nobody can recover the data.';'Keep an offline copy away from the protected computer.'
    )}else{@(
        'RANSOMBACKUP FREE - CHIAVE DI RECUPERO'
        ''
        $RecoveryKey
        ''
        "Account: $Email"
        "Salvata il: $(Get-Date -Format 'dd/MM/yyyy HH:mm')"
        ''
        'RansomBackup non conserva questa chiave.'
        'Senza questa chiave nessuno può recuperare i dati.'
        'Conserva una copia offline, separata dal computer protetto.'
    )}
    $content = $content -join [Environment]::NewLine
    [IO.File]::WriteAllText($dialog.FileName, $content, (New-Object Text.UTF8Encoding($true)))
    return $true
}

function Print-RBRecoveryKey {
    param([Parameter(Mandatory=$true)][string]$RecoveryKey, [string]$Email = '', [ValidateSet('it','en')][string]$Language = 'it')
    $document = New-Object Drawing.Printing.PrintDocument
    $document.DocumentName = 'Chiave di recupero RansomBackup FREE'
    $document.add_PrintPage({
        param($sender, $eventArgs)
        $titleFont = New-Object Drawing.Font('Segoe UI', 18, [Drawing.FontStyle]::Bold)
        $keyFont = New-Object Drawing.Font('Consolas', 17, [Drawing.FontStyle]::Bold)
        $bodyFont = New-Object Drawing.Font('Segoe UI', 11)
        try {
            $brush = [Drawing.Brushes]::Black
            $eventArgs.Graphics.DrawString('RansomBackup FREE', $titleFont, $brush, 70, 70)
            $eventArgs.Graphics.DrawString($(if($Language -eq 'en'){'RECOVERY KEY'}else{'CHIAVE DI RECUPERO'}), $bodyFont, $brush, 70, 120)
            $eventArgs.Graphics.DrawString($RecoveryKey, $keyFont, $brush, 70, 165)
            $eventArgs.Graphics.DrawString("Account: $Email", $bodyFont, $brush, 70, 225)
            $eventArgs.Graphics.DrawString($(if($Language -eq 'en'){'Keep this sheet in a safe place away from the computer.'}else{'Conserva questo foglio in un luogo sicuro e separato dal computer.'}), $bodyFont, $brush, 70, 275)
            $eventArgs.Graphics.DrawString($(if($Language -eq 'en'){'RansomBackup never receives or stores this key.'}else{'RansomBackup non riceve e non conserva questa chiave.'}), $bodyFont, $brush, 70, 305)
            $eventArgs.HasMorePages = $false
        } finally {
            $titleFont.Dispose(); $keyFont.Dispose(); $bodyFont.Dispose()
        }
    })
    $dialog = New-Object Windows.Forms.PrintDialog
    $dialog.Document = $document
    try {
        if ($dialog.ShowDialog() -ne 'OK') { return $false }
        $document.Print()
        return $true
    } finally {
        $dialog.Dispose(); $document.Dispose()
    }
}

function Show-RBRecoveryKeyWindowLegacy {
    param(
        [Parameter(Mandatory=$true)][string]$RecoveryKey,
        [string]$Email = '',
        [ValidateSet('it','en')][string]$Language = 'it',
        [switch]$RequireConfirmation
    )
    $form = New-Object Windows.Forms.Form
    $form.Text = if($Language -eq 'en'){'Recovery key - RansomBackup FREE'}else{'Chiave di recupero - RansomBackup FREE'}
    $form.ClientSize = New-Object Drawing.Size(720, 445)
    $form.StartPosition = 'CenterScreen'
    $form.FormBorderStyle = 'FixedDialog'
    $form.MaximizeBox = $false
    $form.BackColor = [Drawing.Color]::FromArgb(247, 249, 248)
    $form.Font = New-Object Drawing.Font('Segoe UI', 10)
    $form.AutoScaleMode = 'Dpi'

    $header = New-Object Windows.Forms.Panel
    $header.Dock = 'Top'; $header.Height = 92; $header.BackColor = [Drawing.Color]::FromArgb(9, 35, 24)
    $form.Controls.Add($header)
    $title = New-Object Windows.Forms.Label
    $title.Text = if($Language -eq 'en'){'Keep your key safe'}else{'Metti al sicuro la tua chiave'}; $title.ForeColor = [Drawing.Color]::White
    $title.Font = New-Object Drawing.Font('Segoe UI Semibold', 18); $title.Location = New-Object Drawing.Point(28, 18); $title.AutoSize = $true
    $header.Controls.Add($title)
    $subtitle = New-Object Windows.Forms.Label
    $subtitle.Text = if($Language -eq 'en'){'We never receive it: without this key the backup cannot be opened.'}else{'Noi non la riceviamo: senza questa chiave il backup non può essere aperto.'}; $subtitle.ForeColor = [Drawing.Color]::FromArgb(184, 211, 197)
    $subtitle.Location = New-Object Drawing.Point(31, 57); $subtitle.AutoSize = $true; $header.Controls.Add($subtitle)

    $keyBox = New-Object Windows.Forms.TextBox
    $keyBox.Text = $RecoveryKey; $keyBox.ReadOnly = $true; $keyBox.TextAlign = 'Center'
    $keyBox.Font = New-Object Drawing.Font('Consolas', 15, [Drawing.FontStyle]::Bold)
    $keyBox.Location = New-Object Drawing.Point(32, 125); $keyBox.Size = New-Object Drawing.Size(656, 36)
    $form.Controls.Add($keyBox)

    $printButton = New-Object Windows.Forms.Button
    $printButton.Text = if($Language -eq 'en'){'Print the key'}else{'Stampa la chiave'}; $printButton.Location = New-Object Drawing.Point(32, 190); $printButton.Size = New-Object Drawing.Size(190, 42); Set-RBSecondaryButton $printButton
    $saveButton = New-Object Windows.Forms.Button
    $saveButton.Text = if($Language -eq 'en'){'Save to a file'}else{'Salva in un file'}; $saveButton.Location = New-Object Drawing.Point(234, 190); $saveButton.Size = New-Object Drawing.Size(190, 42); Set-RBSecondaryButton $saveButton
    $form.Controls.AddRange(@($printButton, $saveButton))

    $hint = New-Object Windows.Forms.Label
    $hint.Text = if($Language -eq 'en'){'Tip: print the sheet or save the file to a USB drive, not only on this PC.'}else{'Consiglio: stampa il foglio oppure salva il file su una chiavetta USB, non soltanto su questo PC.'}
    $hint.Location = New-Object Drawing.Point(32, 251); $hint.Size = New-Object Drawing.Size(650, 42); $hint.ForeColor = [Drawing.Color]::FromArgb(76, 94, 84)
    $form.Controls.Add($hint)

    $confirm = New-Object Windows.Forms.CheckBox
    $confirm.Text = if($Language -eq 'en'){'I confirm I printed or saved it in a safe place.'}else{'Confermo di averla stampata o salvata in un luogo sicuro.'}
    $confirm.Location = New-Object Drawing.Point(32, 307); $confirm.Size = New-Object Drawing.Size(510, 30)
    $confirm.Visible = [bool]$RequireConfirmation; $form.Controls.Add($confirm)

    $done = New-Object Windows.Forms.Button
    $done.Text = if ($Language -eq 'en') { if($RequireConfirmation){'Continue'}else{'Close'} } else { if($RequireConfirmation){'Continua'}else{'Chiudi'} }
    $done.Location = New-Object Drawing.Point(520, 363); $done.Size = New-Object Drawing.Size(168, 44); Set-RBPrimaryButton $done
    $done.Enabled = -not $RequireConfirmation; $form.Controls.Add($done)
    $confirm.Add_CheckedChanged({ $done.Enabled = $confirm.Checked })
    $printButton.Add_Click({ if (Print-RBRecoveryKey -RecoveryKey $RecoveryKey -Email $Email -Language $Language) { $confirm.Checked = $true } })
    $saveButton.Add_Click({ if (Save-RBRecoveryKeyFile -RecoveryKey $RecoveryKey -Email $Email -Language $Language) { $confirm.Checked = $true } })
    $done.Add_Click({ $form.Tag = 'done'; $form.Close() })
    [void]$form.ShowDialog()
    return ($form.Tag -eq 'done')
}

function Show-RBRecoveryKeyWindow {
    param(
        [Parameter(Mandatory=$true)][string]$RecoveryKey,
        [string]$Email = '',
        [ValidateSet('it','en')][string]$Language = 'it',
        [switch]$RequireConfirmation
    )
    Add-Type -AssemblyName PresentationFramework
    Add-Type -AssemblyName PresentationCore
    Add-Type -AssemblyName WindowsBase
    [xml]$xaml = @'
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Width="760" Height="520" MinWidth="680" MinHeight="480"
        WindowStartupLocation="CenterScreen" Background="#F3F6F4" ResizeMode="CanResize"
        FontFamily="Segoe UI" TextOptions.TextFormattingMode="Display" TextOptions.TextRenderingMode="ClearType"
        UseLayoutRounding="True" SnapsToDevicePixels="True">
  <Window.Resources>
    <Style TargetType="Button">
      <Setter Property="Padding" Value="18,10"/><Setter Property="FontSize" Value="14"/>
      <Setter Property="Cursor" Value="Hand"/><Setter Property="Background" Value="White"/>
      <Setter Property="Foreground" Value="#173D2B"/><Setter Property="BorderBrush" Value="#B7C9BF"/>
    </Style>
  </Window.Resources>
  <Grid>
    <Grid.RowDefinitions><RowDefinition Height="110"/><RowDefinition Height="*"/></Grid.RowDefinitions>
    <Border Grid.Row="0" Background="#092D20">
      <StackPanel Margin="34,22">
        <TextBlock x:Name="TitleText" Foreground="White" FontSize="25" FontWeight="SemiBold"/>
        <TextBlock x:Name="SubtitleText" Foreground="#B8D3C5" FontSize="13" Margin="0,8,0,0" TextWrapping="Wrap"/>
      </StackPanel>
    </Border>
    <Grid Grid.Row="1" Margin="34,26,34,24">
      <Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="*"/></Grid.RowDefinitions>
      <TextBox x:Name="KeyBox" IsReadOnly="True" TextAlignment="Center" FontFamily="Consolas" FontSize="20" FontWeight="Bold" Padding="10" Background="White" BorderBrush="#C7D5CD"/>
      <StackPanel Grid.Row="1" Orientation="Horizontal" Margin="0,18,0,0">
        <Button x:Name="PrintButton" MinWidth="170" Margin="0,0,12,0"/>
        <Button x:Name="SaveButton" MinWidth="170"/>
      </StackPanel>
      <TextBlock Grid.Row="2" x:Name="HintText" Foreground="#567064" FontSize="13" Margin="0,18,0,0" TextWrapping="Wrap"/>
      <CheckBox Grid.Row="3" x:Name="ConfirmBox" Foreground="#173D2B" FontSize="13" Margin="0,20,0,0" VerticalContentAlignment="Center"/>
      <Button Grid.Row="4" x:Name="DoneButton" HorizontalAlignment="Right" VerticalAlignment="Bottom" MinWidth="165" Background="#A7EF70" BorderThickness="0" FontWeight="SemiBold"/>
    </Grid>
  </Grid>
</Window>
'@
    $reader = New-Object System.Xml.XmlNodeReader $xaml
    $window = [Windows.Markup.XamlReader]::Load($reader)
    $titleText=$window.FindName('TitleText'); $subtitleText=$window.FindName('SubtitleText')
    $keyBox=$window.FindName('KeyBox'); $printButton=$window.FindName('PrintButton'); $saveButton=$window.FindName('SaveButton')
    $hintText=$window.FindName('HintText'); $confirmBox=$window.FindName('ConfirmBox'); $doneButton=$window.FindName('DoneButton')
    $window.Title = if($Language -eq 'en'){'Recovery key - RansomBackup FREE'}else{'Chiave di recupero - RansomBackup FREE'}
    $titleText.Text = if($Language -eq 'en'){'Keep your key safe'}else{'Metti al sicuro la tua chiave'}
    $subtitleText.Text = if($Language -eq 'en'){'We never receive it. Without this key the backup cannot be opened.'}else{'Noi non la riceviamo. Senza questa chiave il backup non puo essere aperto.'}
    $keyBox.Text=$RecoveryKey
    $printButton.Content=if($Language -eq 'en'){'Print the key'}else{'Stampa la chiave'}
    $saveButton.Content=if($Language -eq 'en'){'Save to a file'}else{'Salva in un file'}
    $hintText.Text=if($Language -eq 'en'){'Print it or save it to a USB drive kept away from this computer.'}else{'Stampala oppure salvala su una chiavetta USB separata da questo computer.'}
    $confirmBox.Content=if($Language -eq 'en'){'I confirm I printed or saved it in a safe place.'}else{'Confermo di averla stampata o salvata in un luogo sicuro.'}
    $confirmBox.Visibility=if($RequireConfirmation){'Visible'}else{'Collapsed'}
    $doneButton.Content=if($Language -eq 'en'){if($RequireConfirmation){'Continue'}else{'Close'}}else{if($RequireConfirmation){'Continua'}else{'Chiudi'}}
    $doneButton.IsEnabled=-not $RequireConfirmation
    $confirmBox.Add_Checked({$doneButton.IsEnabled=$true}); $confirmBox.Add_Unchecked({$doneButton.IsEnabled=$false})
    $printButton.Add_Click({if(Print-RBRecoveryKey -RecoveryKey $RecoveryKey -Email $Email -Language $Language){$confirmBox.IsChecked=$true}})
    $saveButton.Add_Click({if(Save-RBRecoveryKeyFile -RecoveryKey $RecoveryKey -Email $Email -Language $Language){$confirmBox.IsChecked=$true}})
    $doneButton.Add_Click({$window.Tag='done';$window.Close()})
    $iconPath=New-RBAppIcon
    if($iconPath -and (Test-Path -LiteralPath $iconPath)){$window.Icon=[Windows.Media.Imaging.BitmapFrame]::Create([Uri]$iconPath)}
    if($env:RB_UI_AUTOCLOSE_SECONDS -as [int]){$timer=New-Object Windows.Threading.DispatcherTimer;$timer.Interval=[TimeSpan]::FromSeconds([int]$env:RB_UI_AUTOCLOSE_SECONDS);$timer.Add_Tick({$timer.Stop();$window.Close()});$timer.Start()}
    [void]$window.ShowDialog()
    return ($window.Tag -eq 'done')
}
