param([int]$AutoCloseSeconds=0)
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'Common.ps1')
. (Join-Path $PSScriptRoot 'UIHelpers.ps1')

Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName PresentationCore
Add-Type -AssemblyName WindowsBase
Add-Type -AssemblyName System.Windows.Forms

try { $state=Get-RBConfiguration } catch {
    [Windows.Forms.MessageBox]::Show($_.Exception.Message,'RansomBackup FREE','OK','Error')|Out-Null
    exit 1
}
$en=(Get-RBLanguage $state)-eq 'en'
$quotaText=''
try {
    $account=Get-RBAccountState -State $state
    $quotaGiB=([double]$account.quota_bytes/1GB).ToString('0.##')
    $quotaText=if($en){"Current FREE limit: $quotaGiB GiB of actual stored data."}else{"Limite FREE attuale: $quotaGiB GiB di spazio realmente occupato."}
} catch {
    $quotaText=if($en){'The current limit is available in the main dashboard.'}else{'Il limite aggiornato e disponibile nel pannello principale.'}
}

[xml]$xaml=@'
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Width="820" Height="570" MinWidth="700" MinHeight="500" WindowStartupLocation="CenterScreen"
        Background="#F3F6F4" FontFamily="Segoe UI" ResizeMode="CanResize"
        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="13"/>
      <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="118"/><RowDefinition Height="*"/></Grid.RowDefinitions>
    <Border Grid.Row="0" Background="#092D20">
      <Grid Margin="34,20">
        <Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
        <StackPanel>
          <TextBlock x:Name="TitleText" Foreground="White" FontSize="27" FontWeight="SemiBold"/>
          <TextBlock x:Name="EmailText" Foreground="#B8D3C5" FontSize="13" Margin="0,8,0,0"/>
        </StackPanel>
        <ComboBox Grid.Column="1" x:Name="LanguageBox" Width="125" Height="34" VerticalAlignment="Top" SelectedIndex="0">
          <ComboBoxItem Content="Italiano"/><ComboBoxItem Content="English"/>
        </ComboBox>
      </Grid>
    </Border>
    <Grid Grid.Row="1" Margin="34,24,34,26">
      <Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="Auto"/></Grid.RowDefinitions>
      <TextBlock x:Name="InfoText" Foreground="#567064" FontSize="13" TextWrapping="Wrap"/>
      <Grid Grid.Row="1" Margin="0,18,0,20">
        <Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="150"/></Grid.ColumnDefinitions>
        <ListBox x:Name="FolderList" Background="White" BorderBrush="#C7D5CD" FontSize="13" Padding="8"/>
        <StackPanel Grid.Column="1" Margin="14,0,0,0">
          <Button x:Name="AddButton" Margin="0,0,0,10"/>
          <Button x:Name="RemoveButton" Margin="0,0,0,10"/>
          <Button x:Name="KeyButton" Margin="0,14,0,0"/>
        </StackPanel>
      </Grid>
      <StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Right">
        <Button x:Name="SaveButton" MinWidth="150" Margin="0,0,10,0"/>
        <Button x:Name="BackupButton" MinWidth="195" Background="#A7EF70" BorderThickness="0" FontWeight="SemiBold"/>
      </StackPanel>
    </Grid>
  </Grid>
</Window>
'@
$reader=New-Object System.Xml.XmlNodeReader $xaml
$window=[Windows.Markup.XamlReader]::Load($reader)
$titleText=$window.FindName('TitleText');$emailText=$window.FindName('EmailText');$languageBox=$window.FindName('LanguageBox')
$infoText=$window.FindName('InfoText');$folderList=$window.FindName('FolderList');$addButton=$window.FindName('AddButton')
$removeButton=$window.FindName('RemoveButton');$keyButton=$window.FindName('KeyButton');$saveButton=$window.FindName('SaveButton');$backupButton=$window.FindName('BackupButton')
$window.Title=if($en){'Manage folders - RansomBackup FREE'}else{'Gestisci cartelle - RansomBackup FREE'}
$titleText.Text=if($en){'Protected folders'}else{'Cartelle protette'}
$emailText.Text=$state.Config.email;$languageBox.SelectedIndex=if($en){1}else{0}
$infoText.Text=if($en){"Add every folder you want to protect. $quotaText"}else{"Aggiungi tutte le cartelle che vuoi proteggere. $quotaText"}
$addButton.Content=if($en){'Add folder'}else{'Aggiungi cartella'}
$removeButton.Content=if($en){'Remove'}else{'Rimuovi'}
$keyButton.Content=if($en){'Recovery key'}else{'Chiave di recupero'}
$saveButton.Content=if($en){'Save'}else{'Salva'}
$backupButton.Content=if($en){'Save and back up now'}else{'Salva e avvia backup'}
foreach($source in (Get-RBSources $state)){[void]$folderList.Items.Add([string]$source)}

$addButton.Add_Click({
    $dialog=New-Object Windows.Forms.FolderBrowserDialog
    $dialog.Description=if($en){'Choose a folder to protect'}else{'Scegli una cartella da proteggere'}
    if($dialog.ShowDialog()-eq 'OK' -and -not $folderList.Items.Contains($dialog.SelectedPath)){[void]$folderList.Items.Add($dialog.SelectedPath)}
})
$removeButton.Add_Click({
    if($folderList.SelectedIndex-lt 0){return}
    if($folderList.Items.Count-eq 1){[Windows.Forms.MessageBox]::Show($(if($en){'At least one folder must remain.'}else{'Deve rimanere almeno una cartella.'}),'RansomBackup FREE','OK','Warning')|Out-Null;return}
    $folderList.Items.RemoveAt($folderList.SelectedIndex)
})
$keyButton.Add_Click({[void](Show-RBRecoveryKeyWindow -RecoveryKey $state.Secrets.repository_password -Email $state.Config.email -Language (Get-RBLanguage $state))})
function Save-Folders([bool]$RunBackup){
    try{
        $sources=@($folderList.Items|ForEach-Object{[string]$_})
        Set-RBSources -State $state -Sources $sources
        if($RunBackup){Start-Process wscript.exe -ArgumentList @("`"$(Join-Path $PSScriptRoot 'LaunchHidden.vbs')`"",'Backup.ps1')}
        [Windows.Forms.MessageBox]::Show($(if($en){if($RunBackup){'Folders saved. The backup has started.'}else{'Folders saved.'}}else{if($RunBackup){'Cartelle salvate. Il backup e partito.'}else{'Cartelle salvate.'}}),'RansomBackup FREE','OK','Information')|Out-Null
        $window.Close()
    }catch{[Windows.Forms.MessageBox]::Show($_.Exception.Message,'RansomBackup FREE','OK','Error')|Out-Null}
}
$saveButton.Add_Click({Save-Folders $false});$backupButton.Add_Click({Save-Folders $true})
$languageBox.Add_SelectionChanged({
    if(-not $window.IsLoaded){return}
    $selected=if($languageBox.SelectedIndex-eq 1){'en'}else{'it'}
    if($selected-eq (Get-RBLanguage $state)){return}
    $state.Config|Add-Member -NotePropertyName language -NotePropertyValue $selected -Force
    $state.Config|ConvertTo-Json -Depth 5|Set-Content -LiteralPath $state.Paths.Config -Encoding UTF8
    Start-Process wscript.exe -ArgumentList @("`"$(Join-Path $PSScriptRoot 'LaunchHidden.vbs')`"",'ManageFolders.ps1')
    $window.Close()
})
$iconPath=New-RBAppIcon
if($iconPath -and (Test-Path -LiteralPath $iconPath)){$window.Icon=[Windows.Media.Imaging.BitmapFrame]::Create([Uri]$iconPath)}
if($AutoCloseSeconds-gt 0){$timer=New-Object Windows.Threading.DispatcherTimer;$timer.Interval=[TimeSpan]::FromSeconds($AutoCloseSeconds);$timer.Add_Tick({$timer.Stop();$window.Close()});$timer.Start()}
[void]$window.ShowDialog()
