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

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

function Get-DesktopGallery([string]$prefix, [bool]$german) {
    if ($german) {
        $items = @(
            @('maptools-converter-01-start-de.png', 'Quelldateien öffnen'),
            @('maptools-converter-02-source-selection-de.png', 'Karten- und POI-Quellen auswählen'),
            @('maptools-converter-03-map-area-de.png', 'Kartenausschnitt festlegen'),
            @('maptools-converter-04-output-formats-de.png', 'Inhalte und Ausgabeformate wählen'),
            @('maptools-converter-05-export-review-de.png', 'Exportauftrag prüfen'),
            @('maptools-converter-06-export-complete-de.png', 'Export abgeschlossen')
        )
        $openLabel = 'Bild in Vollbildansicht öffnen'
    } else {
        $items = @(
            @('maptools-converter-01-start-en.png', 'Open source files'),
            @('maptools-converter-02-source-selection-en.png', 'Select map and POI sources'),
            @('maptools-converter-03-map-area-en.png', 'Define the map area'),
            @('maptools-converter-04-output-formats-en.png', 'Choose content and output formats'),
            @('maptools-converter-05-export-review-en.png', 'Review the export job'),
            @('maptools-converter-06-export-complete-en.png', 'Export completed')
        )
        $openLabel = 'Open image fullscreen'
    }

    $figures = for ($index = 0; $index -lt $items.Count; $index++) {
        $file = $items[$index][0]
        $caption = $items[$index][1]
        $step = $index + 1
        '<figure class="feature-shot workflow-shot"><button class="feature-shot-open" type="button" data-lightbox-open aria-label="{0}" title="{0}"><img src="{1}assets/img/{2}" alt="{3}" loading="lazy" width="2302" height="1573"></button><figcaption><span aria-hidden="true">{4}</span><strong>{3}</strong></figcaption></figure>' -f $openLabel, $prefix, $file, $caption, $step
    }
    return '<div class="feature-shot-grid converter-shot-grid">' + ($figures -join '') + '</div>'
}

function Get-MobileSection([string]$prefix, [bool]$german) {
    if ($german) {
        $heading = 'Vom Converter auf das Smartphone'
        $intro = 'Die erzeugten .map- und .poi-Dateien lassen sich anschließend in MapTools importieren und vollständig offline verwenden.'
        $poiCaption = 'POI-Datei in MapTools importieren'
        $mapCaption = 'Erzeugte Karte in MapTools verwenden'
        $openLabel = 'Bild in Vollbildansicht öffnen'
        $poiFile = 'maptools-android-05-poi-import-de.png'
        $mapFile = 'maptools-android-06-map-overview-de.png'
    } else {
        $heading = 'From the Converter to your phone'
        $intro = 'The generated .map and .poi files can then be imported into MapTools and used completely offline.'
        $poiCaption = 'Import the POI file in MapTools'
        $mapCaption = 'Use the generated map in MapTools'
        $openLabel = 'Open image fullscreen'
        $poiFile = 'maptools-android-05-poi-import-en.png'
        $mapFile = 'maptools-android-06-map-overview-en.png'
    }

    return '<section class="section light" id="converter-android"><div class="section-head"><p class="section-kicker">MapTools Android</p><h2>{0}</h2><p>{1}</p></div><div class="phone-shot-grid"><figure class="phone-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="1466" height="3101"></button><figcaption>{5}</figcaption></figure><figure class="phone-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="1466" height="3101"></button><figcaption>{7}</figcaption></figure></div></section>' -f $heading, $intro, $openLabel, $prefix, $poiFile, $poiCaption, $mapFile, $mapCaption
}

$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-DesktopGallery -prefix $prefix -german $isGerman
    $mobileSection = Get-MobileSection -prefix $prefix -german $isGerman

    $galleryPattern = '<div class="feature-shot-grid converter-shot-grid">.*?</div><dialog class="image-lightbox"'
    $html = [Text.RegularExpressions.Regex]::Replace(
        $html,
        $galleryPattern,
        [Text.RegularExpressions.MatchEvaluator]{ param($match) $gallery + '<dialog class="image-lightbox"' },
        [Text.RegularExpressions.RegexOptions]::Singleline
    )

    $mobilePattern = '<section class="section light" id="converter-android">.*?</section>'
    if ([Text.RegularExpressions.Regex]::IsMatch($html, $mobilePattern, [Text.RegularExpressions.RegexOptions]::Singleline)) {
        $html = [Text.RegularExpressions.Regex]::Replace(
            $html,
            $mobilePattern,
            [Text.RegularExpressions.MatchEvaluator]{ param($match) $mobileSection },
            [Text.RegularExpressions.RegexOptions]::Singleline
        )
    } else {
        $portableMarker = '<section class="section light" id="converter-portable">'
        $html = $html.Replace($portableMarker, $mobileSection + $portableMarker)
    }

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

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