param(
    [string]$WebsiteRoot = (Join-Path $PSScriptRoot '..\Webseite')
)

$ErrorActionPreference = 'Stop'
$WebsiteRoot = [IO.Path]::GetFullPath($WebsiteRoot)
$utf8NoBom = [Text.UTF8Encoding]::new($false)

function Get-ElevationGallery([string]$prefix, [bool]$german) {
    if ($german) {
        $heading = 'Neu: Höhendaten zuschneiden und konvertieren'
        $intro = 'HGT-, GeoTIFF-, ASC- und DTED-Höhendaten können einzeln oder zusammen mit Karten und POIs geladen werden. Die Auswahl wird auf der Höhenvorschau festgelegt; der Export bleibt eine eigenständige Höhendatei und wird nicht in die Mapsforge-.map eingebettet.'
        $areaCaption = 'Höhendaten in der Kartenansicht auswählen'
        $formatCaption = 'Zielformat für Höhendaten festlegen'
        $openLabel = 'Bild in Vollbildansicht öffnen'
        $areaFile = 'maptools-converter-elevation-02-area-de.png'
        $formatFile = 'maptools-converter-elevation-03-formats-de.png'
    } else {
        $heading = 'New: crop and convert elevation data'
        $intro = 'HGT, GeoTIFF, ASC and DTED elevation data can be loaded on their own or together with maps and POIs. Define the selection on the terrain preview and export it as a separate elevation file; elevation data is not embedded in the Mapsforge .map file.'
        $areaCaption = 'Select elevation data on the map'
        $formatCaption = 'Choose the elevation output format'
        $openLabel = 'Open image fullscreen'
        $areaFile = 'maptools-converter-elevation-02-area-en.png'
        $formatFile = 'maptools-converter-elevation-03-formats-en.png'
    }

    return '<div class="converter-elevation-intro"><h3>{0}</h3><p>{1}</p></div><div class="feature-shot-grid converter-shot-grid converter-elevation-shot-grid"><figure class="feature-shot"><button class="feature-shot-open" type="button" data-lightbox-open aria-label="{2}" title="{2}"><img src="{3}assets/img/{4}" alt="{5}" loading="lazy" width="2220" height="1390"></button><figcaption>{5}</figcaption></figure><figure class="feature-shot"><button class="feature-shot-open" type="button" data-lightbox-open aria-label="{2}" title="{2}"><img src="{3}assets/img/{6}" alt="{7}" loading="lazy" width="2220" height="1390"></button><figcaption>{7}</figcaption></figure></div>' -f $heading, $intro, $openLabel, $prefix, $areaFile, $areaCaption, $formatFile, $formatCaption
}

$pages = @((Join-Path $WebsiteRoot 'index.html'))
$pages += Get-ChildItem -LiteralPath $WebsiteRoot -Directory |
    ForEach-Object { Join-Path $_.FullName 'index.html' } |
    Where-Object { Test-Path -LiteralPath $_ }

foreach ($page in $pages) {
    $isGerman = [IO.Path]::GetFullPath($page) -eq [IO.Path]::GetFullPath((Join-Path $WebsiteRoot 'index.html'))
    $prefix = if ($isGerman) { './' } else { '../' }
    $html = [IO.File]::ReadAllText($page)
    $gallery = Get-ElevationGallery -prefix $prefix -german $isGerman
    $existingPattern = '<div class="converter-elevation-intro">.*?</div><div class="feature-shot-grid converter-shot-grid converter-elevation-shot-grid">.*?</div>'

    if ([Text.RegularExpressions.Regex]::IsMatch($html, $existingPattern, [Text.RegularExpressions.RegexOptions]::Singleline)) {
        $html = [Text.RegularExpressions.Regex]::Replace(
            $html,
            $existingPattern,
            [Text.RegularExpressions.MatchEvaluator]{ param($match) $gallery },
            [Text.RegularExpressions.RegexOptions]::Singleline
        )
    } else {
        $resultGalleryMarker = '<div class="feature-shot-grid converter-result-shot-grid">'
        if (-not $html.Contains($resultGalleryMarker)) {
            throw "Result gallery marker missing in $page"
        }
        $html = $html.Replace($resultGalleryMarker, $gallery + $resultGalleryMarker)
    }

    [IO.File]::WriteAllText($page, $html, $utf8NoBom)
}

Write-Host "Updated elevation galleries in $($pages.Count) localized homepage files."
