@echo off
setlocal
title EuroTrans - Instalacion completa

echo ==========================================================
echo  EuroTrans - Instalacion completa
echo ==========================================================
echo.
echo Este programa va a:
echo   1. Descargar el launcher de EuroTrans
echo   2. Descomprimirlo en tu Escritorio, en una carpeta "EuroTrans"
echo   3. Instalar Node.js si no lo tienes (puede pedir permiso de
echo      Administrador, es normal)
echo   4. Instalar las dependencias del launcher
echo   5. Abrir tu navegador para que conectes tu wallet (MetaMask o
echo      Immutable Passport)
echo.
echo (Este archivo es autosuficiente: no necesita ningun otro archivo en la
echo  misma carpeta. Todo el script vive dentro de este .bat.)
echo.
pause

powershell -NoProfile -ExecutionPolicy Bypass -Command "& { $marker = 'REM ' + 'EUROTRANS_PS1_START'; $body = (Get-Content -Raw -LiteralPath '%~f0') -split [regex]::Escape($marker), 2; Invoke-Expression $body[1] }"

echo.
echo ==========================================================
echo  Listo. Puedes cerrar esta ventana.
echo ==========================================================
pause
exit /b

REM EUROTRANS_PS1_START
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$ErrorActionPreference = "Stop"

function Write-Step($msg) { Write-Host "`n==> $msg" -ForegroundColor Cyan }
function Write-Ok($msg)   { Write-Host "[OK] $msg" -ForegroundColor Green }
function Write-Warn($msg) { Write-Host "[!] $msg" -ForegroundColor Yellow }
function Write-Err($msg)  { Write-Host "[ERROR] $msg" -ForegroundColor Red }

$zipUrl = "https://ets2.lastgamestudio.fun/setup/downloads/eurotrans-launcher.zip"
$targetDir = Join-Path ([Environment]::GetFolderPath("Desktop")) "EuroTrans"
$installerExe = Join-Path $targetDir "EuroTrans-Instalador.exe"

if (Test-Path $installerExe) {
  Write-Ok "EuroTrans ya esta descargado en $targetDir, no hace falta descargarlo de nuevo."
} else {
  Write-Step "Descargando el launcher de EuroTrans..."
  $zipPath = Join-Path $env:TEMP "eurotrans-launcher.zip"
  try {
    Invoke-WebRequest -Uri $zipUrl -OutFile $zipPath -UseBasicParsing
  } catch {
    Write-Err "No se pudo descargar el launcher: $($_.Exception.Message)"
    Write-Err "Comprueba tu conexion a internet e intenta de nuevo."
    exit 1
  }
  Write-Ok "Descargado."

  Write-Step "Descomprimiendo en $targetDir ..."
  New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
  Expand-Archive -Path $zipPath -DestinationPath $targetDir -Force
  Remove-Item $zipPath -ErrorAction SilentlyContinue
  Write-Ok "Descomprimido."
}

if (-not (Test-Path $installerExe)) {
  Write-Err "No se encontro $installerExe tras descomprimir. Algo salio mal con el paquete descargado."
  exit 1
}

Write-Step "Ejecutando el instalador (Node.js, dependencias, conexion de wallet)..."
Write-Warn "Windows puede pedir permiso de Administrador para instalar Node.js - acepta esa ventana."
Start-Process -FilePath $installerExe -WorkingDirectory $targetDir -Wait
Write-Ok "Instalacion completa. El launcher deberia estar corriendo en una consola nueva."

# Registrar protocolo eurotrans:// para que el boton del dashboard pueda abrir el launcher
try {
  $nodeCmd    = Get-Command node -ErrorAction SilentlyContinue
  $nodeExe    = if ($nodeCmd) { $nodeCmd.Source } else { "$env:ProgramFiles\nodejs\node.exe" }
  $vbsPath    = Join-Path $targetDir "start-launcher.vbs"
  $wscriptExe = Join-Path $env:SystemRoot "System32\wscript.exe"
  # Escribir VBS linea a linea en ASCII puro (sin BOM) para que wscript.exe lo compile sin errores
  $lines = @(
    'Dim oShell, oFso, launcherDir, nodeExe, src',
    'Set oShell = CreateObject("WScript.Shell")',
    'Set oFso   = CreateObject("Scripting.FileSystemObject")',
    'launcherDir = oFso.GetParentFolderName(WScript.ScriptFullName)',
    'src = launcherDir & "\src\index.js"',
    "nodeExe = `"$nodeExe`"",
    'If Not oFso.FileExists(nodeExe) Then nodeExe = "node"',
    'oShell.Run Chr(34) & nodeExe & Chr(34) & " " & Chr(34) & src & Chr(34), 1, False',
    'Dim wmi, procs',
    'Set wmi   = GetObject("winmgmts:\\.\root\cimv2")',
    'Set procs = wmi.ExecQuery("SELECT * FROM Win32_Process WHERE Name=''eurotrucks2.exe''")',
    'If procs.Count = 0 Then oShell.Run "steam://rungameid/227300", 1, False'
  )
  [System.IO.File]::WriteAllLines($vbsPath, $lines, [System.Text.Encoding]::ASCII)
  $command = "`"$wscriptExe`" `"$vbsPath`" `"%1`""
  $regBase = "HKCU:\SOFTWARE\Classes\eurotrans"
  New-Item -Path $regBase -Force | Out-Null
  Set-ItemProperty -Path $regBase -Name "(Default)" -Value "URL:EuroTrans Protocol" -Force
  New-ItemProperty -Path $regBase -Name "URL Protocol" -Value "" -PropertyType String -Force | Out-Null
  New-Item -Path "$regBase\shell\open\command" -Force | Out-Null
  Set-ItemProperty -Path "$regBase\shell\open\command" -Name "(Default)" -Value $command -Force
  Write-Ok "Protocolo eurotrans:// registrado. El boton 'Iniciar EuroTrans' del dashboard ya puede abrir el launcher."
} catch {
  Write-Warn "No se pudo registrar el protocolo eurotrans://: $_"
}
