param(
  [ValidateSet("Menu", "Instalar", "Desinstalar")]
  [string]$Acao = "Menu"
)

$ErrorActionPreference = "Stop"
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyles()

$setupVersion = "2.8.4"
$packageRoot = Split-Path $PSScriptRoot
$installerEngine = Join-Path $PSScriptRoot "instalar-nativo.ps1"
$uninstallerEngine = Join-Path $PSScriptRoot "desinstalar-nativo.ps1"
$termsFile = Join-Path $packageRoot "TERMOS-DE-USO.txt"
$logoFile = Join-Path $packageRoot "SetupBanner.png"
$iconFile = Join-Path $packageRoot "NativoSistemas.ico"
$installRoot = Join-Path $env:LOCALAPPDATA "AmbrosiaNativo"
$uninstallKey = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\AmbrosiaNativo"
$acceptanceKey = "HKCU:\Software\Nativo Sistemas\Ambrosia Nativo"

$installerAvailable = Test-Path -LiteralPath $installerEngine -PathType Leaf
$uninstallerAvailable = Test-Path -LiteralPath $uninstallerEngine -PathType Leaf
$installedVersion = $null
try { $installedVersion = (Get-ItemProperty -LiteralPath $uninstallKey -ErrorAction Stop).DisplayVersion } catch { }
$hasLocalInstall = (Test-Path -LiteralPath $installRoot -PathType Container) -or $installedVersion

if (-not (Test-Path -LiteralPath $termsFile -PathType Leaf)) {
  throw "O arquivo TERMOS-DE-USO.txt nao foi encontrado. Extraia o ZIP inteiro antes de continuar."
}

$dark = [System.Drawing.Color]::FromArgb(47, 33, 27)
$orange = [System.Drawing.Color]::FromArgb(245, 106, 42)
$cream = [System.Drawing.Color]::FromArgb(250, 247, 243)
$green = [System.Drawing.Color]::FromArgb(20, 122, 76)
$muted = [System.Drawing.Color]::FromArgb(109, 94, 84)

$form = New-Object System.Windows.Forms.Form
$form.Text = "Ambrosia Nativo Setup v$setupVersion"
$form.StartPosition = "CenterScreen"
$form.FormBorderStyle = "FixedSingle"
$form.MaximizeBox = $false
$form.MinimizeBox = $true
$form.ClientSize = New-Object System.Drawing.Size(780, 635)
$form.BackColor = $cream
$form.Font = New-Object System.Drawing.Font("Segoe UI", 10)
if (Test-Path -LiteralPath $iconFile -PathType Leaf) {
  try { $form.Icon = New-Object System.Drawing.Icon($iconFile) } catch { }
}

$header = New-Object System.Windows.Forms.Panel
$header.Location = New-Object System.Drawing.Point(0, 0)
$header.Size = New-Object System.Drawing.Size(780, 142)
$header.BackColor = $dark
$form.Controls.Add($header)

$logo = New-Object System.Windows.Forms.PictureBox
$logo.Location = New-Object System.Drawing.Point(24, 18)
$logo.Size = New-Object System.Drawing.Size(145, 104)
$logo.SizeMode = "Zoom"
$logo.BackColor = $dark
if (Test-Path -LiteralPath $logoFile -PathType Leaf) {
  try { $logo.Image = [System.Drawing.Image]::FromFile($logoFile) } catch { }
}
$header.Controls.Add($logo)

$title = New-Object System.Windows.Forms.Label
$title.Text = "AMBROSIA NATIVO"
$title.Location = New-Object System.Drawing.Point(188, 28)
$title.Size = New-Object System.Drawing.Size(430, 36)
$title.ForeColor = [System.Drawing.Color]::White
$title.Font = New-Object System.Drawing.Font("Segoe UI", 21, [System.Drawing.FontStyle]::Bold)
$header.Controls.Add($title)

$subtitle = New-Object System.Windows.Forms.Label
$subtitle.Text = "Instalador, atualizador e desinstalador"
$subtitle.Location = New-Object System.Drawing.Point(191, 69)
$subtitle.Size = New-Object System.Drawing.Size(420, 24)
$subtitle.ForeColor = [System.Drawing.Color]::FromArgb(233, 216, 204)
$subtitle.Font = New-Object System.Drawing.Font("Segoe UI", 10)
$header.Controls.Add($subtitle)

$versionBadge = New-Object System.Windows.Forms.Label
$versionBadge.Text = "VERSAO $setupVersion"
$versionBadge.Location = New-Object System.Drawing.Point(638, 31)
$versionBadge.Size = New-Object System.Drawing.Size(112, 30)
$versionBadge.TextAlign = "MiddleCenter"
$versionBadge.BackColor = $orange
$versionBadge.ForeColor = [System.Drawing.Color]::White
$versionBadge.Font = New-Object System.Drawing.Font("Segoe UI", 9, [System.Drawing.FontStyle]::Bold)
$header.Controls.Add($versionBadge)

$status = New-Object System.Windows.Forms.Label
if ($installedVersion -eq $setupVersion) {
  $status.Text = "VERSAO v$setupVersion JA INSTALADA  >  MODO REPARAR"
}
elseif ($installedVersion) {
  $status.Text = "INSTALADO: v$installedVersion  >  DISPONIVEL: v$setupVersion"
}
elseif ($hasLocalInstall) {
  $status.Text = "INSTALACAO ANTERIOR DETECTADA  >  ATUALIZAR PARA v$setupVersion"
}
else {
  $status.Text = "PRONTO PARA INSTALAR A VERSAO $setupVersion"
}
$status.Location = New-Object System.Drawing.Point(190, 101)
$status.Size = New-Object System.Drawing.Size(560, 24)
$status.ForeColor = [System.Drawing.Color]::FromArgb(116, 211, 157)
$status.Font = New-Object System.Drawing.Font("Segoe UI", 9, [System.Drawing.FontStyle]::Bold)
$header.Controls.Add($status)

$sectionTitle = New-Object System.Windows.Forms.Label
$sectionTitle.Text = "TERMOS DE USO E LICENCA"
$sectionTitle.Location = New-Object System.Drawing.Point(28, 161)
$sectionTitle.Size = New-Object System.Drawing.Size(420, 28)
$sectionTitle.ForeColor = $dark
$sectionTitle.Font = New-Object System.Drawing.Font("Segoe UI", 12, [System.Drawing.FontStyle]::Bold)
$form.Controls.Add($sectionTitle)

$termsBox = New-Object System.Windows.Forms.TextBox
$termsBox.Location = New-Object System.Drawing.Point(28, 194)
$termsBox.Size = New-Object System.Drawing.Size(724, 262)
$termsBox.Multiline = $true
$termsBox.ReadOnly = $true
$termsBox.ScrollBars = "Vertical"
$termsBox.BackColor = [System.Drawing.Color]::White
$termsBox.ForeColor = [System.Drawing.Color]::FromArgb(62, 52, 46)
$termsBox.Font = New-Object System.Drawing.Font("Segoe UI", 9)
$termsBox.Text = [System.IO.File]::ReadAllText($termsFile, [System.Text.Encoding]::UTF8)
$form.Controls.Add($termsBox)

$accept = New-Object System.Windows.Forms.CheckBox
$accept.Text = "Li e aceito os Termos de Uso e Licenca."
$accept.Location = New-Object System.Drawing.Point(31, 473)
$accept.Size = New-Object System.Drawing.Size(470, 26)
$accept.ForeColor = $dark
$accept.Font = New-Object System.Drawing.Font("Segoe UI", 10, [System.Drawing.FontStyle]::Bold)
$form.Controls.Add($accept)

$info = New-Object System.Windows.Forms.Label
$info.Text = "A atualizacao preserva os dados e cria um backup automatico antes de instalar."
$info.Location = New-Object System.Drawing.Point(31, 507)
$info.Size = New-Object System.Drawing.Size(720, 22)
$info.ForeColor = $muted
$info.Font = New-Object System.Drawing.Font("Segoe UI", 9)
$form.Controls.Add($info)

$installButton = New-Object System.Windows.Forms.Button
if ($installedVersion -eq $setupVersion) {
  $installButton.Text = "REPARAR v$setupVersion"
}
elseif ($installedVersion -or $hasLocalInstall) {
  $installButton.Text = "ATUALIZAR PARA v$setupVersion"
}
else {
  $installButton.Text = "INSTALAR v$setupVersion"
}
$installButton.Location = New-Object System.Drawing.Point(28, 548)
$installButton.Size = New-Object System.Drawing.Size(298, 52)
$installButton.FlatStyle = "Flat"
$installButton.FlatAppearance.BorderSize = 0
$installButton.BackColor = $orange
$installButton.ForeColor = [System.Drawing.Color]::White
$installButton.Font = New-Object System.Drawing.Font("Segoe UI", 10, [System.Drawing.FontStyle]::Bold)
$installButton.Cursor = "Hand"
$installButton.Enabled = $installerAvailable
$form.Controls.Add($installButton)

$uninstallButton = New-Object System.Windows.Forms.Button
$uninstallButton.Text = "DESINSTALAR"
$uninstallButton.Location = New-Object System.Drawing.Point(342, 548)
$uninstallButton.Size = New-Object System.Drawing.Size(190, 52)
$uninstallButton.FlatStyle = "Flat"
$uninstallButton.FlatAppearance.BorderColor = $dark
$uninstallButton.FlatAppearance.BorderSize = 2
$uninstallButton.BackColor = $cream
$uninstallButton.ForeColor = $dark
$uninstallButton.Font = New-Object System.Drawing.Font("Segoe UI", 10, [System.Drawing.FontStyle]::Bold)
$uninstallButton.Cursor = "Hand"
$uninstallButton.Enabled = $uninstallerAvailable -and $hasLocalInstall
$form.Controls.Add($uninstallButton)

$cancelButton = New-Object System.Windows.Forms.Button
$cancelButton.Text = "CANCELAR"
$cancelButton.Location = New-Object System.Drawing.Point(548, 548)
$cancelButton.Size = New-Object System.Drawing.Size(204, 52)
$cancelButton.FlatStyle = "Flat"
$cancelButton.FlatAppearance.BorderSize = 0
$cancelButton.BackColor = [System.Drawing.Color]::FromArgb(224, 217, 211)
$cancelButton.ForeColor = $dark
$cancelButton.Font = New-Object System.Drawing.Font("Segoe UI", 10, [System.Drawing.FontStyle]::Bold)
$cancelButton.Cursor = "Hand"
$form.Controls.Add($cancelButton)

if ($Acao -eq "Desinstalar") {
  $sectionTitle.Text = "MANUTENCAO DA INSTALACAO"
  $accept.Enabled = $false
  $installButton.Enabled = $false
  $info.Text = "Escolha DESINSTALAR. Voce podera preservar ou apagar os dados locais."
}

$script:setupAction = $null
$script:deleteData = $false

$installButton.Add_Click({
  if (-not $accept.Checked) {
    [System.Windows.Forms.MessageBox]::Show(
      "Para instalar ou atualizar, marque a opcao de aceite dos Termos de Uso.",
      "Aceite necessario",
      [System.Windows.Forms.MessageBoxButtons]::OK,
      [System.Windows.Forms.MessageBoxIcon]::Information
    ) | Out-Null
    return
  }
  $script:setupAction = "install"
  $form.Close()
})

$uninstallButton.Add_Click({
  $choice = [System.Windows.Forms.MessageBox]::Show(
    "Deseja apagar tambem os dados do restaurante?`r`n`r`nSIM: apaga programa, mesas, pedidos, usuarios, configuracoes e backups.`r`nNAO: remove somente o programa e preserva os dados (recomendado).`r`nCANCELAR: volta ao instalador.",
    "Opcoes de desinstalacao",
    [System.Windows.Forms.MessageBoxButtons]::YesNoCancel,
    [System.Windows.Forms.MessageBoxIcon]::Question,
    [System.Windows.Forms.MessageBoxDefaultButton]::Button2
  )
  if ($choice -eq [System.Windows.Forms.DialogResult]::Cancel) { return }
  $script:deleteData = $choice -eq [System.Windows.Forms.DialogResult]::Yes
  if ($script:deleteData) {
    $confirm = [System.Windows.Forms.MessageBox]::Show(
      "Todos os dados e backups locais serao apagados definitivamente. Deseja continuar?",
      "Confirmar exclusao dos dados",
      [System.Windows.Forms.MessageBoxButtons]::YesNo,
      [System.Windows.Forms.MessageBoxIcon]::Warning,
      [System.Windows.Forms.MessageBoxDefaultButton]::Button2
    )
    if ($confirm -ne [System.Windows.Forms.DialogResult]::Yes) { return }
  }
  $script:setupAction = "uninstall"
  $form.Close()
})

$cancelButton.Add_Click({ $form.Close() })
$form.CancelButton = $cancelButton
if ($Acao -eq "Instalar") { $form.AcceptButton = $installButton }

[void]$form.ShowDialog()
if ($logo.Image) { $logo.Image.Dispose() }
$form.Dispose()

try {
  if ($script:setupAction -eq "install") {
    New-Item -Path $acceptanceKey -Force | Out-Null
    Set-ItemProperty -Path $acceptanceKey -Name "TermosAceitosVersao" -Value "1.0"
    Set-ItemProperty -Path $acceptanceKey -Name "TermosAceitosEm" -Value (Get-Date).ToString("s")
    Set-ItemProperty -Path $acceptanceKey -Name "SetupVersao" -Value $setupVersion
    & $installerEngine -TermosAceitos
  }
  elseif ($script:setupAction -eq "uninstall") {
    if ($script:deleteData) {
      & $uninstallerEngine -ApagarDados -ConfirmadoPeloSetup
    }
    else {
      & $uninstallerEngine -PreservarDados -ConfirmadoPeloSetup
    }
  }
}
catch {
  [System.Windows.Forms.MessageBox]::Show(
    $_.Exception.Message,
    "Falha no Ambrosia Setup",
    [System.Windows.Forms.MessageBoxButtons]::OK,
    [System.Windows.Forms.MessageBoxIcon]::Error
  ) | Out-Null
  throw
}
