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

Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName PresentationCore
Add-Type -AssemblyName WindowsBase

function Open-RBTool([string]$Name) {
    Start-Process wscript.exe -ArgumentList @("`"$(Join-Path $PSScriptRoot 'LaunchHidden.vbs')`"", "`"$Name`"")
}

if (-not $Preview) {
    try { $script:state = Get-RBConfiguration } catch {
        Open-RBTool 'SetupWizard.ps1'
        exit 0
    }
} else {
    $script:state = [pscustomobject]@{
        Config = [pscustomobject]@{ email='cliente@example.com'; language='it'; gateway='https://free.ransombackup.com' }
        Paths = [pscustomobject]@{ Status=''; Logs=$env:TEMP }
    }
}
$script:en = (Get-RBLanguage $script:state) -eq 'en'

[xml]$xaml = @'
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="RansomBackup FREE" Width="1020" Height="740" MinWidth="860" MinHeight="600"
        WindowStartupLocation="CenterScreen" Background="#F3F6F4"
        FontFamily="Segoe UI" TextOptions.TextFormattingMode="Display"
        TextOptions.TextRenderingMode="ClearType" UseLayoutRounding="True" SnapsToDevicePixels="True">
  <Window.Resources>
    <Style TargetType="Button" x:Key="PrimaryButton">
      <Setter Property="Background" Value="#A7EF70"/><Setter Property="Foreground" Value="#0C291B"/>
      <Setter Property="BorderThickness" Value="0"/><Setter Property="Padding" Value="22,12"/>
      <Setter Property="FontWeight" Value="SemiBold"/><Setter Property="FontSize" Value="14"/>
      <Setter Property="Cursor" Value="Hand"/>
      <Setter Property="Template"><Setter.Value><ControlTemplate TargetType="Button">
        <Border Background="{TemplateBinding Background}" CornerRadius="8" Padding="{TemplateBinding Padding}">
          <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
        </Border>
      </ControlTemplate></Setter.Value></Setter>
    </Style>
    <Style TargetType="Button" x:Key="SecondaryButton" BasedOn="{StaticResource PrimaryButton}">
      <Setter Property="Background" Value="#FFFFFF"/><Setter Property="Foreground" Value="#173D2B"/>
    </Style>
    <Style TargetType="Button" x:Key="LinkButton" BasedOn="{StaticResource PrimaryButton}">
      <Setter Property="Background" Value="Transparent"/><Setter Property="Foreground" Value="#D8E9DF"/>
      <Setter Property="Padding" Value="12,8"/><Setter Property="FontSize" Value="13"/>
    </Style>
    <Style TargetType="Border" x:Key="Card">
      <Setter Property="Background" Value="White"/><Setter Property="CornerRadius" Value="14"/>
      <Setter Property="Padding" Value="24"/><Setter Property="Effect"><Setter.Value>
        <DropShadowEffect BlurRadius="18" ShadowDepth="2" Opacity="0.10" Color="#173D2B"/>
      </Setter.Value></Setter>
    </Style>
  </Window.Resources>
  <Grid>
    <Grid.RowDefinitions><RowDefinition Height="150"/><RowDefinition Height="*"/><RowDefinition Height="34"/></Grid.RowDefinitions>
    <Border Grid.Row="0" Background="#092D20">
      <Grid Margin="42,25">
        <Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
        <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
          <Border Width="62" Height="62" CornerRadius="18" Background="#A7EF70" Margin="0,0,20,0">
            <Grid>
              <Path Fill="#092D20" Stretch="Uniform" Margin="17" Data="M12,2 L21,6 V12 C21,17.1 17.6,21.7 12,23 C6.4,21.7 3,17.1 3,12 V6 Z M8,12 L11,15 L17,9"/>
            </Grid>
          </Border>
          <StackPanel VerticalAlignment="Center">
            <TextBlock Text="RansomBackup FREE" Foreground="White" FontSize="28" FontWeight="SemiBold"/>
            <TextBlock x:Name="HeaderSubtitle" Foreground="#B8D3C5" FontSize="14" Margin="1,5,0,0"/>
          </StackPanel>
        </StackPanel>
        <StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center">
          <Button x:Name="AccountButton" Style="{StaticResource LinkButton}" Margin="0,0,8,0"/>
          <Button x:Name="RefreshButton" Style="{StaticResource LinkButton}"/>
        </StackPanel>
      </Grid>
    </Border>

    <Grid Grid.Row="1" Margin="42,28,42,18">
      <Grid.ColumnDefinitions><ColumnDefinition Width="1.65*"/><ColumnDefinition Width="20"/><ColumnDefinition Width="1*"/></Grid.ColumnDefinitions>
      <Grid.RowDefinitions><RowDefinition Height="230"/><RowDefinition Height="20"/><RowDefinition Height="*"/></Grid.RowDefinitions>

      <Border Grid.Column="0" Grid.Row="0" Style="{StaticResource Card}">
        <Grid>
          <Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="*"/></Grid.RowDefinitions>
          <DockPanel>
            <StackPanel DockPanel.Dock="Left">
              <TextBlock x:Name="StatusEyebrow" Text="STATO DEL BACKUP" Foreground="#668173" FontSize="11" FontWeight="Bold"/>
              <TextBlock x:Name="StatusTitle" Text="Controllo in corso..." Foreground="#102D20" FontSize="27" FontWeight="SemiBold" Margin="0,7,0,0" TextWrapping="Wrap"/>
            </StackPanel>
            <Border x:Name="StatusBadge" Background="#E8F7DC" CornerRadius="14" Padding="12,6" HorizontalAlignment="Right" VerticalAlignment="Top">
              <TextBlock x:Name="StatusBadgeText" Text="ONLINE" Foreground="#256132" FontWeight="Bold" FontSize="11"/>
            </Border>
          </DockPanel>
          <TextBlock Grid.Row="1" x:Name="LastBackupText" Foreground="#567064" FontSize="14" Margin="0,14,0,0"/>
          <Button Grid.Row="2" x:Name="BackupButton" Style="{StaticResource PrimaryButton}" HorizontalAlignment="Left" Margin="0,22,0,0"/>
          <TextBlock Grid.Row="3" x:Name="ActionFeedback" Foreground="#256132" FontSize="13" Margin="0,14,0,0" TextWrapping="Wrap"/>
        </Grid>
      </Border>

      <Border Grid.Column="2" Grid.Row="0" Style="{StaticResource Card}">
        <Grid>
          <Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="*"/></Grid.RowDefinitions>
          <TextBlock x:Name="SpaceTitle" Foreground="#668173" FontSize="11" FontWeight="Bold"/>
          <TextBlock Grid.Row="1" x:Name="UsageValue" Text="-" Foreground="#102D20" FontSize="30" FontWeight="SemiBold" Margin="0,9,0,0" TextWrapping="Wrap"/>
          <ProgressBar Grid.Row="2" x:Name="UsageBar" Height="10" Minimum="0" Maximum="100" Margin="0,18,0,0" Foreground="#56B879" Background="#E7EEE9" BorderThickness="0"/>
          <TextBlock Grid.Row="3" x:Name="UsageDetail" Foreground="#567064" FontSize="13" Margin="0,12,0,0" TextWrapping="Wrap"/>
          <TextBlock Grid.Row="4" x:Name="QuotaHint" Foreground="#7D5A27" FontSize="12" Margin="0,15,0,0" TextWrapping="Wrap"/>
        </Grid>
      </Border>

      <Border Grid.Column="0" Grid.Row="2" Style="{StaticResource Card}">
        <Grid>
          <Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="Auto"/></Grid.RowDefinitions>
          <TextBlock x:Name="FoldersTitle" Foreground="#102D20" FontSize="19" FontWeight="SemiBold"/>
          <ListBox Grid.Row="1" x:Name="FoldersList" Margin="0,14,0,12" BorderThickness="0" Background="Transparent" Foreground="#365547" FontSize="13"/>
          <Button Grid.Row="2" x:Name="FoldersButton" Style="{StaticResource SecondaryButton}" HorizontalAlignment="Left"/>
        </Grid>
      </Border>

      <Border Grid.Column="2" Grid.Row="2" Style="{StaticResource Card}">
        <Grid>
          <Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="*"/></Grid.RowDefinitions>
          <TextBlock x:Name="ToolsTitle" Foreground="#102D20" FontSize="19" FontWeight="SemiBold"/>
          <Button Grid.Row="1" x:Name="RestoreButton" Style="{StaticResource SecondaryButton}" HorizontalContentAlignment="Left" Margin="0,14,0,0"/>
          <Button Grid.Row="2" x:Name="KeyButton" Style="{StaticResource SecondaryButton}" HorizontalContentAlignment="Left" Margin="0,8,0,0"/>
          <Button Grid.Row="3" x:Name="LogsButton" Style="{StaticResource SecondaryButton}" HorizontalContentAlignment="Left" Margin="0,8,0,0"/>
          <TextBlock Grid.Row="4" x:Name="SecurityNote" Foreground="#668173" FontSize="11" TextWrapping="Wrap" VerticalAlignment="Bottom" Margin="0,14,0,0"/>
        </Grid>
      </Border>
    </Grid>
    <TextBlock Grid.Row="2" x:Name="FooterText" HorizontalAlignment="Center" Foreground="#789084" FontSize="11"/>
  </Grid>
</Window>
'@

$reader = New-Object System.Xml.XmlNodeReader $xaml
$window = [Windows.Markup.XamlReader]::Load($reader)
$names = 'HeaderSubtitle','AccountButton','RefreshButton','StatusEyebrow','StatusTitle','StatusBadge','StatusBadgeText','LastBackupText','BackupButton','ActionFeedback','SpaceTitle','UsageValue','UsageBar','UsageDetail','QuotaHint','FoldersTitle','FoldersList','FoldersButton','ToolsTitle','RestoreButton','KeyButton','LogsButton','SecurityNote','FooterText'
foreach ($name in $names) { Set-Variable -Name $name -Value $window.FindName($name) }

if ($script:en) {
    $HeaderSubtitle.Text = "Protected account - $($script:state.Config.email)"
    $AccountButton.Content='MY ACCOUNT'; $RefreshButton.Content='REFRESH'; $StatusEyebrow.Text='BACKUP STATUS'
    $BackupButton.Content='Back up now'; $SpaceTitle.Text='FREE STORAGE'; $FoldersTitle.Text='Protected folders'
    $FoldersButton.Content='Manage folders'; $ToolsTitle.Text='TOOLS'; $RestoreButton.Content='Restore files'
    $KeyButton.Content='Recovery key'; $LogsButton.Content='Technical log'
    $SecurityNote.Text='Your data is encrypted on this PC. RansomBackup never receives the recovery key.'
    $FooterText.Text="RansomBackup FREE - client $script:RBClientVersion"
} else {
    $HeaderSubtitle.Text = "Account protetto - $($script:state.Config.email)"
    $AccountButton.Content='AREA PERSONALE'; $RefreshButton.Content='AGGIORNA'; $StatusEyebrow.Text='STATO DEL BACKUP'
    $BackupButton.Content='Esegui backup adesso'; $SpaceTitle.Text='SPAZIO FREE'; $FoldersTitle.Text='Cartelle protette'
    $FoldersButton.Content='Gestisci cartelle'; $ToolsTitle.Text='STRUMENTI'; $RestoreButton.Content='Ripristina file'
    $KeyButton.Content='Chiave di recupero'; $LogsButton.Content='Registro tecnico'
    $SecurityNote.Text='I dati vengono cifrati su questo PC. RansomBackup non riceve mai la chiave di recupero.'
    $FooterText.Text="RansomBackup FREE - client $script:RBClientVersion"
}

function Format-RBSize([int64]$Bytes) {
    if ($Bytes -ge 1GB) { return ('{0:0.00} GiB' -f ($Bytes / 1GB)) }
    if ($Bytes -ge 1MB) { return ('{0:0} MiB' -f ($Bytes / 1MB)) }
    return ('{0:0} KiB' -f ([Math]::Max(0, $Bytes) / 1KB))
}

function Update-RBDashboard {
    $FoldersList.Items.Clear()
    if ($Preview) {
        $account = [pscustomobject]@{ used_bytes=734003200; quota_bytes=2147483648; quota_state='normal'; active=$true; last_snapshot_at=[DateTimeOffset]::UtcNow.AddHours(-3).ToUnixTimeSeconds() }
        $sources = @('C:\Documenti','C:\Foto clienti')
    } else {
        $sources = @(Get-RBSources $script:state)
        try {
            $account = Get-RBAccountState -State $script:state
            $StatusBadge.Background = '#E8F7DC'; $StatusBadgeText.Foreground = '#256132'; $StatusBadgeText.Text = 'ONLINE'
        } catch {
            $account = $null
            $StatusBadge.Background = '#FDE9E5'; $StatusBadgeText.Foreground = '#A13D2D'; $StatusBadgeText.Text = 'OFFLINE'
            $ActionFeedback.Text = if($script:en){'The server cannot be reached. Local settings are still available.'}else{"Il server non e' raggiungibile. Le impostazioni locali restano disponibili."}
        }
    }
    foreach ($source in $sources) { [void]$FoldersList.Items.Add("-  $source") }
    if (-not $account) {
        $StatusTitle.Text = if($script:en){'Unable to verify'}else{'Verifica non disponibile'}
        $LastBackupText.Text = if($script:en){'Check your Internet connection and try again.'}else{'Controlla la connessione Internet e riprova.'}
        return
    }
    $used = [int64]$account.used_bytes; $quota = [int64]$account.quota_bytes
    $percent = if($quota -gt 0){[Math]::Min(100,[Math]::Round($used*100/$quota,1))}else{0}
    $UsageBar.Value = $percent
    $UsageValue.Text = "$(Format-RBSize $used)  /  $(Format-RBSize $quota)"
    $UsageDetail.Text = if($script:en){"$percent% used - usage is based on actual stored data"}else{"$percent% utilizzato - si conta lo spazio realmente occupato"}
    $QuotaHint.Text = if($account.quota_state -in @('grace','blocked')) {
        if($script:en){'The FREE limit has been reached. New backups are suspended.'}else{"Il limite FREE e' stato raggiunto. I nuovi backup sono sospesi."}
    } elseif($percent -ge 70) {
        if($script:en){'Your archive is filling up. Review the options in your account.'}else{"L'archivio si sta riempiendo. Controlla le opzioni nell'area personale."}
    } else { '' }
    if ($account.last_snapshot_at) {
        $last = [DateTimeOffset]::FromUnixTimeSeconds([int64]$account.last_snapshot_at).LocalDateTime
        $StatusTitle.Text = if($script:en){'Your files are protected'}else{'I tuoi file sono protetti'}
        $LastBackupText.Text = if($script:en){"Last backup: $($last.ToString('g'))"}else{"Ultimo backup: $($last.ToString('g'))"}
    } else {
        $StatusTitle.Text = if($script:en){'First backup pending'}else{'Primo backup in attesa'}
        $LastBackupText.Text = if($script:en){'Start the first backup to protect your folders.'}else{'Avvia il primo backup per proteggere le cartelle.'}
    }
}

$AccountButton.Add_Click({ Open-RBTool 'Status.ps1' })
$RefreshButton.Add_Click({ Update-RBDashboard })
$FoldersButton.Add_Click({ Open-RBTool 'ManageFolders.ps1' })
$RestoreButton.Add_Click({ Open-RBTool 'Restore.ps1' })
$KeyButton.Add_Click({ Open-RBTool 'RecoveryKey.ps1' })
$LogsButton.Add_Click({ if(Test-Path $script:state.Paths.Logs){Start-Process explorer.exe -ArgumentList @("`"$($script:state.Paths.Logs)`"")} })
$BackupButton.Add_Click({
    if ($Preview) { $ActionFeedback.Text = if($script:en){'Preview: backup started.'}else{'Anteprima: backup avviato.'}; return }
    Open-RBTool 'Backup.ps1'
    $ActionFeedback.Text = if($script:en){'Backup started. You can continue using the computer.'}else{'Backup avviato. Puoi continuare a usare il computer.'}
})

Update-RBDashboard
$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()
