<?php
declare(strict_types=1);
require __DIR__ . '/site-lib.php';
$albums = array_values(array_filter(reportage_albums(), static function ($album): bool {
    $name = (string)($album['name'] ?? '');
    $title = (string)($album['title'] ?? '');
    $url = (string)($album['url'] ?? '');
    $identity = strtolower(preg_replace('/[^a-z0-9]/i', '', $name . ' ' . $title . ' ' . $url) ?? '');
    $isNotreDame = str_contains($identity, 'reportageroyan') || str_contains($identity, 'notredamederoyan');
    return stripos($name, 'La Roche-Guyon') === false && stripos($title, 'La Roche-Guyon') === false
        && !$isNotreDame;
}));
$lapidialesEntry = [
    'name' => 'Les Lapidiales',
    'title' => 'Les Lapidiales — La Galaxie des pierres levées',
    'place' => 'Crazannes · Charente-Maritime',
    'category' => 'PATRIMOINE · SCULPTURE',
    'description' => 'Aux anciennes carrières de Crazannes, les Lapidiales réunissent sculptures monumentales, bas-reliefs et parcours de la Galaxie des Pierres Levées.',
    'cover' => 'albums/Les%20Lapidiales/images/galaxie/dans-le-sous-bois-des-visages-monumentaux-emergent-dune-composition-de-pierre-foisonnante.jpg',
    'url' => 'albums/Les%20Lapidiales/index.html',
    'photo_count' => 133,
];
$lapidialesIndex = null;
foreach ($albums as $candidateIndex => $candidateAlbum) {
    $candidateIdentity = strtolower(preg_replace('/[^a-z0-9]/i', '', (string)($candidateAlbum['name'] ?? '') . ' ' . (string)($candidateAlbum['title'] ?? '')) ?? '');
    if (str_contains($candidateIdentity, 'lapidiales') || str_contains($candidateIdentity, 'galaxiedespierreslevees')) {
        $lapidialesIndex = $candidateIndex;
        break;
    }
}
if ($lapidialesIndex === null) {
    $albums[] = $lapidialesEntry;
} else {
    $albums[$lapidialesIndex] = array_merge($albums[$lapidialesIndex], $lapidialesEntry);
}
$albumBase = realpath(__DIR__ . '/albums');
$albumConfig = reportage_config();
foreach ($albums as $albumIndex => $album) {
    if (!$albumBase) continue;
    $albumName = (string)($album['name'] ?? '');
    $albumRoot = realpath($albumBase . DIRECTORY_SEPARATOR . $albumName);
    if (!$albumRoot || !is_dir($albumRoot) || !str_starts_with($albumRoot, $albumBase . DIRECTORY_SEPARATOR)) continue;
    if ($albumName === 'Les Lapidiales') {
        $albums[$albumIndex] = array_merge($album, $lapidialesEntry);
        continue;
    }
    $albumMeta = is_array($albumConfig[$albumName] ?? null) ? $albumConfig[$albumName] : [];
    $isMemorial = stripos($albumName . ' ' . (string)($album['title'] ?? ''), 'Mémorial de la Résistance de Chasseneuil-sur-Bonnieure') !== false;
    if ($isMemorial) {
        $albums[$albumIndex]['description'] = 'À Chasseneuil-sur-Bonnieure, le mémorial et la nécropole rendent hommage aux résistants et aux soldats morts pour la France. Ce reportage suit les lignes du monument, les inscriptions et les allées du lieu de mémoire.';
        $albums[$albumIndex]['url'] = 'albums/' . rawurlencode($albumName) . '/index.html';
    }
    if (stripos($albumName . ' ' . (string)($album['title'] ?? ''), 'Sentiers des Arts') !== false) {
        $albums[$albumIndex]['description'] = 'Depuis 2013, les Sentiers des Arts invitent à parcourir une galerie à ciel ouvert où la création contemporaine, le patrimoine et les paysages se répondent. Ce reportage réunit des fresques, des sculptures et des installations, avec leurs matières, leurs couleurs et les histoires qu’elles racontent.';
    }
    $albumDir = reportage_album_directory($albumBase, $albumName, $albumMeta);
    if (!$albumDir) continue;
    $albumImages = reportage_images($albumDir);
    if (stripos($albumName, 'Sentiers des Arts') !== false) {
        $albumImages = array_values(array_filter($albumImages, static fn($file): bool => $file !== 'photo-06.jpg' && !(stripos($file, 'panneau') !== false && stripos($file, 'Karinka') !== false)));
    }
    $albums[$albumIndex]['photo_count'] = count($albumImages);
    $coverUrl = trim((string)($album['cover'] ?? ''));
    $coverPath = $coverUrl !== '' ? parse_url($coverUrl, PHP_URL_PATH) : false;
    $coverLocal = is_string($coverPath) && $coverPath !== '' ? realpath(__DIR__ . '/' . ltrim(rawurldecode($coverPath), '/')) : false;
    $siteRoot = realpath(__DIR__);
    if ($coverLocal && is_file($coverLocal) && $siteRoot && str_starts_with($coverLocal, $siteRoot . DIRECTORY_SEPARATOR)) continue;
    $firstPhoto = $albumImages[0] ?? '';
    if ($firstPhoto === '') continue;
    $photoDir = (string)($albumMeta['photo_dir'] ?? $albumName);
    $albums[$albumIndex]['cover'] = reportage_asset_url('albums/' . $photoDir . '/' . $firstPhoto);
    if ($isMemorial) {
        $albums[$albumIndex]['cover'] = reportage_asset_url('albums/' . $photoDir . '/Mémorial Chasseneuil (20)-printemps.jpg');
    }
}
$egliseMadeleineCover = 'albums/Eglise-Sainte-Madeleine/images/photo-01.jpg';
foreach ($albums as $albumIndex => $album) {
    $egliseIdentity = strtolower(preg_replace('/[^a-z0-9]/i', '', (string)($album['name'] ?? '') . ' ' . (string)($album['title'] ?? '') . ' ' . (string)($album['url'] ?? '')) ?? '');
    if (str_contains($egliseIdentity, 'eglisesaintemadeleine')) {
        // La couverture reste hors du dossier des photos, et la carte ouvre la vraie page du reportage.
        $albums[$albumIndex]['cover'] = $egliseMadeleineCover;
        $albums[$albumIndex]['url'] = 'albums/Eglise-Sainte-Madeleine/index.html';
        $albums[$albumIndex]['cover_caption_title'] = 'Au seuil de la fresque';
        $albums[$albumIndex]['cover_caption'] = 'Sous l’arche, le regard s’ouvre sur la fresque monumentale d’Amaury Dubois. Les courbes crème et orangées avancent sur le bleu profond et conduisent vers le chœur.';
        break;
    }
}
$autoireEntry = [
    'name' => 'Architecture & Patrimoine',
    'title' => 'Autoire',
    'place' => 'Autoire · Lot',
    'category' => 'PATRIMOINE',
    'description' => 'Une promenade photographique dans le village d’Autoire, entre maisons de pierre, cascade, falaises calcaires et vestiges du Château des Anglais.',
    'cover' => reportage_asset_url('albums/Autoire/images/couverture-autoire.jpg'),
    'url' => 'albums/Autoire/index.html',
    'photo_count' => 35,
];
$autoireIndex = null;
foreach ($albums as $candidateIndex => $candidateAlbum) {
    $identity = strtolower(preg_replace('/[^a-z0-9]/i', '', (string)($candidateAlbum['name'] ?? '') . ' ' . (string)($candidateAlbum['title'] ?? '')) ?? '');
    if (str_contains($identity, 'autoire') || str_contains($identity, 'architecturepatrimoine')) {
        $autoireIndex = $candidateIndex;
        break;
    }
}
if ($autoireIndex === null) {
    $albums[] = $autoireEntry;
} else {
    $albums[$autoireIndex] = array_merge($albums[$autoireIndex], $autoireEntry);
}
$ileMadameEntry = [
    'name' => 'Ile-Madame-au-rythme-des-marees',
    'title' => 'L’île Madame, au rythme des marées',
    'place' => 'Port-des-Barques · Charente-Maritime',
    'category' => 'PAYSAGE · PATRIMOINE',
    'description' => 'Une promenade photographique entre la Passe aux Bœufs, les paysages changeants de l’estran, les carrelets et les pierres du fort.',
    'cover' => 'albums/Ile-Madame-au-rythme-des-marees/photos/Ile%20Madame%20%281%29.jpg',
    'url' => 'albums/Ile-Madame-au-rythme-des-marees/index.html',
    'photo_count' => 45,
];
$ileMadameIndex = null;
foreach ($albums as $candidateIndex => $candidateAlbum) {
    $candidateName = (string)($candidateAlbum['name'] ?? '');
    $candidateTitle = (string)($candidateAlbum['title'] ?? '');
    if (stripos($candidateName, 'Ile-Madame-au-rythme-des-marees') !== false
        || stripos($candidateTitle, 'au rythme des marées') !== false) {
        $ileMadameIndex = $candidateIndex;
        break;
    }
}
if ($ileMadameIndex === null) {
    $albums[] = $ileMadameEntry;
} else {
    $albums[$ileMadameIndex] = array_merge($albums[$ileMadameIndex], $ileMadameEntry);
}
$manoirFolder = 'Le “Manoir de Mademoiselle” est un manoir du XIXᵉ siècle situé sur le domaine d\'un ancien vignoble à Segonzac,';
if ($albumBase) {
    foreach (scandir($albumBase) ?: [] as $folderName) {
        if ($folderName === '.' || $folderName === '..') continue;
        $folderIdentity = strtolower(preg_replace('/[^a-z0-9]/i', '', $folderName) ?? '');
        if ((str_contains($folderIdentity, 'manoirdemademoiselle') || str_contains($folderIdentity, 'manoirreportagefinal')) && is_dir($albumBase . DIRECTORY_SEPARATOR . $folderName)) {
            $manoirFolder = $folderName;
            break;
        }
    }
}
$manoirEntry = [
    'name' => $manoirFolder,
    'title' => 'Le “Manoir de Mademoiselle”',
    'place' => 'Segonzac · Charente',
    'category' => 'PATRIMOINE · VIGNOBLE',
    'description' => 'Un manoir du XIXᵉ siècle sur le domaine d’un ancien vignoble à Segonzac. Le reportage traverse ses pièces, ses souvenirs familiaux et les traces de son histoire viticole.',
    'cover' => '',
    'url' => 'albums/' . rawurlencode($manoirFolder) . '/index.html',
    'photo_count' => 93,
];
// Le helper encode lui-même les espaces et accents : lui passer le chemin brut évite un double encodage.
$manoirCoverName = "Belle Époque (années 1880 à 1914) ou d'ambiance de maison de campagne du début du siècle.jpg";
$manoirEntry['cover'] = reportage_asset_url('albums/' . $manoirFolder . '/' . $manoirCoverName);
$manoirIndex = null;
foreach ($albums as $candidateIndex => $candidateAlbum) {
    $candidateIdentity = strtolower(preg_replace('/[^a-z0-9]/i', '', (string)($candidateAlbum['name'] ?? '') . ' ' . (string)($candidateAlbum['title'] ?? '') . ' ' . (string)($candidateAlbum['url'] ?? '')) ?? '');
    if (str_contains($candidateIdentity, 'manoirdemademoiselle') || str_contains($candidateIdentity, 'manoirreportagefinal')) {
        $manoirIndex = $candidateIndex;
        break;
    }
}
if ($manoirIndex === null) {
    $albums[] = $manoirEntry;
} else {
    $albums[$manoirIndex] = array_merge($albums[$manoirIndex], $manoirEntry);
}
// Le reportage mis à la une est déterminé automatiquement : le dossier de reportage
// le plus récemment ajouté/modifié dans /albums et possédant un index.html passe en tête.
// Repli de sécurité sur l’Île Madame si aucun dossier valide n’est détecté.
$featured = null;
$featuredModifiedAt = -1;
$royanAlbumEntry = null;
$laRochePhotoDir = __DIR__ . '/albums/La Roche-Guyon/photos';
$laRochePhotoCount = is_dir($laRochePhotoDir) ? count(reportage_images($laRochePhotoDir)) : 0;
if ($albumBase) {
    foreach (scandir($albumBase) ?: [] as $folderName) {
        if ($folderName === '.' || $folderName === '..' || stripos($folderName, 'La Roche-Guyon') !== false
            || $folderName === '@eaDir' || $folderName === '#recycle') continue;
        $folderPath = $albumBase . DIRECTORY_SEPARATOR . $folderName;
        $folderRoot = realpath($folderPath);
        if (!$folderRoot || !is_dir($folderRoot) || !str_starts_with($folderRoot, $albumBase . DIRECTORY_SEPARATOR)) continue;
        $pageName = is_file($folderRoot . '/index.html') ? 'index.html' : (is_file($folderRoot . '/index.php') ? 'index.php' : '');
        if ($pageName === '') continue;

        $candidate = null;
        foreach ($albums as $album) {
            if ((string)($album['name'] ?? '') === $folderName) {
                $candidate = $album;
                break;
            }
        }
        $albumMeta = is_array($albumConfig[$folderName] ?? null) ? $albumConfig[$folderName] : [];
        $folderIdentity = strtolower(preg_replace('/[^a-z0-9]/i', '', $folderName) ?? '');
        $isGanil = str_contains($folderIdentity, 'chemindehalagedeganil');
        $isRoyan = str_contains($folderIdentity, 'reportageroyan') || str_contains($folderIdentity, 'notredamederoyan');

        if ($isGanil) {
            $ganilPhotoDir = $folderRoot . '/photos';
            $ganilPhotos = is_dir($ganilPhotoDir) ? reportage_images($ganilPhotoDir) : [];
            $ganilCover = in_array('ganil-28.jpg', $ganilPhotos, true) ? 'ganil-28.jpg' : ($ganilPhotos[0] ?? '');
            if ($ganilCover !== '') {
                $relativeGanil = str_replace(DIRECTORY_SEPARATOR, '/', substr($ganilPhotoDir, strlen($albumBase) + 1));
                $encodedGanil = implode('/', array_map('rawurlencode', explode('/', $relativeGanil)));
                $candidate = [
                    'name' => $folderName,
                    'title' => 'Le chemin de halage de Ganil',
                    'place' => 'Bouziès · Saint-Cirq-Lapopie · Lot',
                    'category' => 'PAYSAGE · PATRIMOINE',
                    'description' => 'Une promenade photographique le long du Lot, entre falaise calcaire, bas-relief et mémoire des gabares.',
                    'cover' => reportage_asset_url('albums/' . $encodedGanil . '/' . rawurlencode($ganilCover)),
                    'url' => 'albums/' . rawurlencode($folderName) . '/' . $pageName,
                    'photo_count' => count($ganilPhotos),
                ];
                foreach ($albums as $existingIndex => $existingAlbum) {
                    $existingIdentity = strtolower(preg_replace('/[^a-z0-9]/i', '', (string)($existingAlbum['name'] ?? '') . ' ' . (string)($existingAlbum['title'] ?? '')) ?? '');
                    if (str_contains($existingIdentity, 'chemindehalagedeganil')) {
                        $albums[$existingIndex] = array_merge($existingAlbum, $candidate);
                        break;
                    }
                }
            }
        }
        if ($isRoyan) {
            $royanPhotoDir = $folderRoot . '/photos';
            $royanPhotos = is_dir($royanPhotoDir) ? reportage_images($royanPhotoDir) : [];
            $royanCover = $royanPhotos[0] ?? '';
            if ($royanCover !== '') {
                $relativeRoyan = str_replace(DIRECTORY_SEPARATOR, '/', substr($royanPhotoDir, strlen($albumBase) + 1));
                $encodedRoyan = implode('/', array_map('rawurlencode', explode('/', $relativeRoyan)));
                $candidate = [
                    'name' => 'Notre-Dame de Royan',
                    'title' => 'Notre-Dame de Royan',
                    'place' => 'Royan · Charente-Maritime',
                    'category' => 'ARCHITECTURE · PATRIMOINE',
                    'description' => 'Découvrez Notre-Dame de Royan, chef-d’œuvre de l’architecture moderne inauguré en 1958, à travers son histoire et ses détails photographiés.',
                    'cover' => reportage_asset_url('albums/' . $encodedRoyan . '/' . rawurlencode($royanCover)),
                    'url' => 'albums/' . rawurlencode($folderName) . '/' . $pageName,
                    'photo_count' => count($royanPhotos),
                ];
                if ($royanAlbumEntry === null || str_contains($folderIdentity, 'notredamederoyan')) $royanAlbumEntry = $candidate;
            }
        }
        if ($candidate === null) {
            $photoDir = reportage_album_directory($albumBase, $folderName, $albumMeta);
            $photos = $photoDir ? reportage_images($photoDir) : [];
            if (!$photos) {
                foreach (['photos', 'images'] as $childPhotoDir) {
                    $possiblePhotoDir = $folderRoot . DIRECTORY_SEPARATOR . $childPhotoDir;
                    if (is_dir($possiblePhotoDir)) {
                        $photoDir = $possiblePhotoDir;
                        $photos = reportage_images($photoDir);
                        if ($photos) break;
                    }
                }
            }
            $relativePhotoDir = $photoDir ? str_replace(DIRECTORY_SEPARATOR, '/', substr($photoDir, strlen($albumBase) + 1)) : '';
            $encodedPhotoDir = implode('/', array_map('rawurlencode', explode('/', $relativePhotoDir)));
            $cover = isset($photos[0]) && $encodedPhotoDir !== ''
                ? reportage_asset_url('albums/' . $encodedPhotoDir . '/' . rawurlencode($photos[0]))
                : '';
            $candidate = [
                'name' => $folderName,
                'title' => (string)($albumMeta['title'] ?? str_replace(['-', '_'], ' ', $folderName)),
                'place' => (string)($albumMeta['place'] ?? ''),
                'category' => (string)($albumMeta['category'] ?? ''),
                'description' => (string)($albumMeta['description'] ?? ''),
                'cover' => $cover,
                'url' => 'albums/' . rawurlencode($folderName) . '/' . $pageName,
                'photo_count' => count($photos),
            ];
        }
        // Ajouter automatiquement tout nouveau dossier-reportage à la liste sans modifier
        // les fiches déjà connues : leur titre, vignette, texte et apparence restent intacts.
        $existingAlbumIndex = null;
        $expectedAlbumPrefix = 'albums/' . rawurlencode($folderName) . '/';
        $expectedAlbumPrefixDecoded = 'albums/' . $folderName . '/';
        foreach ($albums as $existingIndex => $existingAlbum) {
            $existingName = (string)($existingAlbum['name'] ?? '');
            $existingUrl = ltrim((string)($existingAlbum['url'] ?? ''), '/');
            if ($existingName === $folderName
                || str_starts_with($existingUrl, $expectedAlbumPrefix)
                || str_starts_with(rawurldecode($existingUrl), $expectedAlbumPrefixDecoded)) {
                $existingAlbumIndex = $existingIndex;
                break;
            }
        }
        if ($existingAlbumIndex === null) {
            $albums[] = $candidate;
            $existingAlbumIndex = array_key_last($albums);
        }

        // Un nouveau reportage publié avec index.html devient automatiquement « À LA UNE ».
        // On utilise le dossier/index le plus récent et on force le lien vers son index.html.
        if ($pageName === 'index.html') {
            $folderMtime = (int)(@filemtime($folderRoot) ?: 0);
            $indexMtime = (int)(@filemtime($folderRoot . DIRECTORY_SEPARATOR . 'index.html') ?: 0);
            $folderCtime = (int)(@filectime($folderRoot) ?: 0);
            $indexCtime = (int)(@filectime($folderRoot . DIRECTORY_SEPARATOR . 'index.html') ?: 0);
            $candidateModifiedAt = max($folderMtime, $indexMtime, $folderCtime, $indexCtime);

            if ($candidateModifiedAt > $featuredModifiedAt) {
                $featuredModifiedAt = $candidateModifiedAt;
                $featured = $albums[$existingAlbumIndex] ?? $candidate;
                $featured['url'] = 'albums/' . rawurlencode($folderName) . '/index.html';

                // Si la fiche existante n’a pas de vignette exploitable, reprendre celle du dossier.
                if (empty($featured['cover']) && !empty($candidate['cover'])) {
                    $featured['cover'] = $candidate['cover'];
                }
                if (empty($featured['photo_count']) && !empty($candidate['photo_count'])) {
                    $featured['photo_count'] = $candidate['photo_count'];
                }
            }
        }
    }
}
if ($featured === null) {
    $featured = $ileMadameEntry;
}
// Assurer l’affichage de la carte et de la vignette du reportage Lavardin.
$lavardinCover = 'albums/Lavardin/images/01-le-pont-sur-le-loir-nuageux.png';
$lavardinEntry = [
    'name' => 'Lavardin',
    'title' => 'Lavardin',
    'place' => 'Vallée du Loir · Loir-et-Cher',
    'category' => 'PATRIMOINE · VILLAGE',
    'description' => 'Une promenade photographique entre le vieux pont sur le Loir, le château médiéval et l’église Saint-Genest.',
    'cover' => $lavardinCover,
    'url' => 'albums/Lavardin/index.html',
];
$lavardinAlbumIndex = null;
foreach ($albums as $lavardinIndex => $lavardinAlbum) {
    $lavardinIdentity = strtolower(preg_replace('/[^a-z0-9]/i', '', (string)($lavardinAlbum['name'] ?? '') . ' ' . (string)($lavardinAlbum['title'] ?? '') . ' ' . (string)($lavardinAlbum['url'] ?? '')) ?? '');
    if (str_contains($lavardinIdentity, 'lavardin')) {
        $lavardinAlbumIndex = $lavardinIndex;
        break;
    }
}
if ($lavardinAlbumIndex === null) {
    $albums[] = $lavardinEntry;
} else {
    // Seule la vignette est remplacée : les autres informations existantes restent intactes.
    $albums[$lavardinAlbumIndex]['cover'] = $lavardinCover;
}
if ($featured !== null) {
    $featuredIdentity = strtolower(preg_replace('/[^a-z0-9]/i', '', (string)($featured['name'] ?? '') . ' ' . (string)($featured['title'] ?? '') . ' ' . (string)($featured['url'] ?? '')) ?? '');
    if (str_contains($featuredIdentity, 'lavardin')) {
        $featured['cover'] = $lavardinCover;
    }
}

// Le dossier Saint-Céneri ne possède pas de page index publiée.
// Ouvrir le reportage via le gestionnaire d’albums présent à la racine.
foreach ($albums as &$album) {
    $albumIdentity = (string)($album['name'] ?? '') . ' ' . (string)($album['title'] ?? '');
    if (stripos($albumIdentity, 'Saint-Céneri-le-Gérei') !== false) {
        $albumName = (string)($album['name'] ?? 'Saint-Céneri-le-Gérei');
        $album['url'] = 'album.php?d=' . rawurlencode($albumName);
    }
}
unset($album);

if ($royanAlbumEntry !== null) {
    $hasRoyan = false;
    foreach ($albums as $album) {
        $identity = strtolower(preg_replace('/[^a-z0-9]/i', '', (string)($album['name'] ?? '') . ' ' . (string)($album['title'] ?? '') . ' ' . (string)($album['url'] ?? '')) ?? '');
        if (str_contains($identity, 'reportageroyan') || str_contains($identity, 'notredamederoyan')) {
            $hasRoyan = true;
            break;
        }
    }
    if (!$hasRoyan) $albums[] = $royanAlbumEntry;
}
$featuredUrl = $featured['url'] ?? reportage_url((string)($featured['name'] ?? ''));
$featuredShareUrl = 'https://voleurdimages.fr/' . ltrim((string)$featuredUrl, '/');
$featuredFacebookTarget = $featuredShareUrl;
$featuredWhatsAppTarget = $featuredShareUrl;
$featuredSharePath = parse_url($featuredShareUrl, PHP_URL_PATH);
$featuredShareLocal = is_string($featuredSharePath) ? realpath(__DIR__ . '/' . ltrim(rawurldecode($featuredSharePath), '/')) : false;
$siteRoot = realpath(__DIR__);
if (is_string($featuredSharePath) && preg_match('~/index\.html$~i', $featuredSharePath) === 1 && $featuredShareLocal && is_file($featuredShareLocal) && $siteRoot && str_starts_with($featuredShareLocal, $siteRoot . DIRECTORY_SEPARATOR)) {
    $featuredPreviewUrl = 'https://voleurdimages.fr/share-preview.php?p=' . rawurlencode($featuredSharePath) . '&v=' . rawurlencode((string)(time() . '-' . random_int(100000, 999999)));
    $featuredFacebookTarget = $featuredPreviewUrl;
    $featuredWhatsAppTarget = $featuredPreviewUrl;
}
$featuredFacebookShare = 'https://www.facebook.com/sharer/sharer.php?u=' . rawurlencode($featuredFacebookTarget);
$featuredWhatsAppShare = 'https://api.whatsapp.com/send?text=' . rawurlencode((string)($featured['title'] ?? 'Reportage photo') . ' — ' . $featuredWhatsAppTarget);
// Métadonnées WhatsApp de la page d’accueil : utiliser la couverture du reportage mis en avant.
$featuredImageUrl = $featured && !empty($featured['cover'])
    ? 'https://voleurdimages.fr/' . ltrim((string)$featured['cover'], '/')
    : '';
$featuredImagePath = $featuredImageUrl !== '' ? parse_url($featuredImageUrl, PHP_URL_PATH) : false;
$featuredImageLocal = is_string($featuredImagePath)
    ? realpath(__DIR__ . '/' . ltrim(rawurldecode($featuredImagePath), '/'))
    : false;
$siteRoot = realpath(__DIR__);
$shareImageInfo = $featuredImageLocal && is_file($featuredImageLocal) && $siteRoot
    && str_starts_with($featuredImageLocal, $siteRoot . DIRECTORY_SEPARATOR)
    ? @getimagesize($featuredImageLocal)
    : false;
$shareImageUrl = $featuredImageUrl !== ''
    ? $featuredImageUrl . (str_contains($featuredImageUrl, '?') ? '&' : '?') . 'v=20261020-facebook-preview-5'
    : '';
$featuredImageSize = $featuredImageLocal && is_file($featuredImageLocal) ? filesize($featuredImageLocal) : false;
$fallbackSharePath = __DIR__ . '/images/facebook/phare-solitaire.jpg';
if ((!is_array($shareImageInfo) || ($featuredImageSize !== false && $featuredImageSize > 580000)) && is_file($fallbackSharePath) && filesize($fallbackSharePath) <= 580000) {
    $shareImageUrl = 'https://voleurdimages.fr/images/facebook/phare-solitaire.jpg?v=20261020-facebook-preview-5';
    $shareImageInfo = @getimagesize($fallbackSharePath);
}
$homeShareNonce = time() . '-' . mt_rand(100000, 999999);
$homeWhatsAppTarget = 'https://voleurdimages.fr/index.php?partage=' . rawurlencode($homeShareNonce);
$homeFacebookTarget = $homeWhatsAppTarget;
$homeFacebookShare = 'https://www.facebook.com/sharer/sharer.php?u=' . rawurlencode($homeFacebookTarget);
$homeOpenGraphUrl = 'https://voleurdimages.fr/index.php';
if (isset($_GET['partage']) && is_scalar($_GET['partage']) && preg_match('/^[A-Za-z0-9_-]{1,64}$/D', (string)$_GET['partage']) === 1) {
    $homeOpenGraphUrl .= '?partage=' . rawurlencode((string)$_GET['partage']);
}
$categories = array_values(array_unique(array_filter(array_column($albums, 'category'))));
?><!doctype html>
<html lang="fr"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="description" content="Reportages photographiques de Helis Denis : patrimoine, paysages, nature et ambiances nocturnes.">
<title>Voleur d’images — Reportages photo de Helis Denis</title>
<meta property="og:type" content="website"><meta property="og:site_name" content="Voleur d’images — Helis Denis"><meta property="og:title" content="Voleur d’images — Reportages photo"><meta property="og:description" content="Reportages photographiques de Helis Denis : patrimoine, paysages, nature et ambiances nocturnes."><meta property="og:url" content="<?= h($homeOpenGraphUrl) ?>"><meta property="og:image" content="<?= h($shareImageUrl) ?>"><meta property="og:image:secure_url" content="<?= h($shareImageUrl) ?>"><meta property="og:image:alt" content="<?= h((string)($featured['title'] ?? 'Reportages photo de Helis Denis')) ?>"><?php if(is_array($shareImageInfo)): ?><meta property="og:image:type" content="<?= h((string)($shareImageInfo['mime'] ?? 'image/jpeg')) ?>"><meta property="og:image:width" content="<?= (int)$shareImageInfo[0] ?>"><meta property="og:image:height" content="<?= (int)$shareImageInfo[1] ?>"><?php endif; ?><meta name="twitter:image" content="<?= h($shareImageUrl) ?>"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="Voleur d’images — Reportages photo"><meta name="twitter:description" content="Reportages photographiques de Helis Denis : patrimoine, paysages, nature et ambiances nocturnes.">
<link rel="stylesheet" href="assets/reportage.css"><link rel="stylesheet" href="automne-vif.css?v=20261015">
<style>.guestbook-float{position:fixed;z-index:20;right:1.25rem;bottom:1.25rem;display:flex;align-items:center;gap:.35rem;padding:.85rem 1.1rem;border-radius:999px;background:#8d4e2c;color:#fff;text-decoration:none;font-weight:700;box-shadow:0 6px 22px #24190f38}.guestbook-float:hover,.guestbook-float:focus-visible{background:#69391f;transform:translateY(-2px)}@media(max-width:600px){.guestbook-float{right:.75rem;bottom:.75rem;padding:.75rem 1rem}.guestbook-float span{display:none}}.feature-section .section-heading{position:relative;justify-content:center!important}.feature-section .section-heading>div{width:100%;text-align:center}.feature-section .section-heading .featured-main-heading{margin:0 auto!important;font-family:"Arial Black","Trebuchet MS",Arial,sans-serif!important;font-weight:900!important;font-style:italic!important;font-size:clamp(2.2rem,4vw,3.6rem)!important;line-height:1.05!important;letter-spacing:-.02em;color:var(--accent,#b7642a)!important;text-align:center!important}.feature-section .section-heading .section-index{position:absolute;right:0}.story-share-actions{margin-top:.55rem}.story-share-actions .share-button{display:inline-flex;align-items:center;gap:.4rem}</style>
</head><body id="top">
<header class="topbar"><a class="brand" href="index.php"><span class="brand-mark">V</span><span>VOLEUR D’IMAGES<small>HELIS DENIS · REPORTAGES PHOTO</small></span></a>
<nav aria-label="Navigation principale"><a href="#reportages">Reportages</a><a href="#galeries">Tous les albums</a><a href="livre-or.php">Livre d’or</a><a href="#auteur">À propos</a></nav>
<div class="topbar-actions"><span class="site-shares" aria-label="Partager la page d’accueil"><a data-home-facebook-share data-home-url="<?= h($homeWhatsAppTarget) ?>" href="<?= h($homeFacebookShare) ?>" target="_blank" rel="noopener noreferrer" aria-label="Partager cette page sur Facebook" title="Partager sur Facebook">f</a><a data-home-whatsapp-share data-home-url="<?= h($homeWhatsAppTarget) ?>" href="https://api.whatsapp.com/send?text=<?= rawurlencode('Voleur d’images — '.$homeWhatsAppTarget) ?>" target="_blank" rel="noopener noreferrer" aria-label="Partager cette page sur WhatsApp" title="Partager sur WhatsApp">↗</a></span><a class="top-cta" href="#galeries">Explorer <span aria-hidden="true">↗</span></a></div></header>
<main>
<section class="intro"<?php if($featured && $featured['cover']): ?> style="--hero-image:url('<?= h($featured['cover']) ?>')"<?php endif; ?>><div class="intro-copy"><p class="eyebrow"><span></span> LE MONDE AU GRÉ DE MES VISITES</p><h1 style="text-transform:none!important">Regards sur une France magnifique&nbsp;!</h1><p class="intro-lead"><em>Des paysages, des villages et des instants saisis au fil des chemins et des rencontres.</em></p><a class="button" href="#reportages">Découvrir le reportage <span>↓</span></a></div>
<div class="intro-note"><span class="note-number">HD</span><span>Helis Denis<br>photographe de terrain</span></div><div class="hero-caption"><?= $featured ? h($featured['place'] ?: $featured['title']) : 'Mes reportages en images' ?> <span>· © Helis Denis</span></div></section>

<?php if ($featured): ?><section id="reportages" class="feature-section"><div class="section-heading"><div><h2 class="featured-main-heading">À LA UNE</h2></div><span class="section-index">01 / <?= str_pad((string)max(1,count($albums) + (($featured['name'] ?? '') === 'Notre-Dame de Royan' ? 2 : 1)),2,'0',STR_PAD_LEFT) ?></span></div>
<div class="feature-card"><a class="feature-image feature-image-link" href="<?= h($featuredUrl) ?>"><?php if ($featured['cover']): ?><img src="<?= h($featured['cover']) ?>" alt="<?= h($featured['title']) ?>" loading="eager"><?php endif; ?><span class="image-label">REPORTAGE PHOTO</span></a><div class="feature-copy"><p class="eyebrow"><?= h($featured['category'] ?: 'CARNET DE VOYAGE') ?><?= $featured['place'] ? ' · '.h($featured['place']) : '' ?></p><h3><?= h($featured['title']) ?></h3><p><?= h($featured['description'] ?: 'Une promenade photographique, au fil des lieux, des lumières et des détails.') ?></p><div class="reportage-rating" data-reportage-rating data-album="<?= h($featured['name']) ?>"><span class="reportage-rating-value">Notez ce reportage</span><div class="reportage-rating-stars" role="group" aria-label="Noter ce reportage sur 5"><?php for($star=1;$star<=5;$star++): ?><button type="button" data-rating-value="<?= $star ?>" aria-label="<?= $star ?> étoile<?= $star>1?'s':'' ?> sur 5" aria-pressed="false">☆</button><?php endfor; ?></div></div><a class="text-link" href="<?= h($featuredUrl) ?>">Lire le reportage <b aria-hidden="true">↗</b></a><div class="share-actions feature-share-actions" aria-label="Partager le reportage du moment"><span class="share-label">Partager ce reportage</span><a class="share-button share-facebook" href="<?= h($featuredFacebookShare) ?>" target="_blank" rel="noopener noreferrer"><span aria-hidden="true">f</span> Facebook</a><a class="share-button share-whatsapp" href="<?= h($featuredWhatsAppShare) ?>" target="_blank" rel="noopener noreferrer"><span aria-hidden="true">↗</span> WhatsApp</a></div></div></div></section><?php endif; ?>

<section id="galeries" class="albums-section"><div class="section-heading"><div><p class="eyebrow">LE CARNET DE TERRAIN</p><h2>Les autres reportages</h2><p class="section-intro">Une sélection de promenades, de lieux et de rencontres.</p></div><label class="search-wrap"><span aria-hidden="true">⌕</span><input id="album-search" type="search" placeholder="Rechercher un lieu…" aria-label="Rechercher un reportage"></label></div>
<div class="filters" aria-label="Filtrer par thème"><button class="filter active" data-filter="all">Tout voir</button><?php foreach ($categories as $cat): ?><button class="filter" data-filter="<?= h(lower_fr($cat)) ?>"><?= h($cat) ?></button><?php endforeach; ?></div>
<div class="story-grid" id="story-grid">
<?php foreach ($albums as $album): if ($featured && $album['name']===$featured['name']) continue; $albumUrl = $album['url'] ?? reportage_url($album['name']); $albumWhatsAppTarget = 'https://voleurdimages.fr/' . ltrim((string)$albumUrl, '/'); $albumSharePath = parse_url($albumWhatsAppTarget, PHP_URL_PATH); $albumShareLocal = is_string($albumSharePath) ? realpath(__DIR__ . '/' . ltrim(rawurldecode($albumSharePath), '/')) : false; if (is_string($albumSharePath) && preg_match('~/index\.html$~i', $albumSharePath) === 1 && $albumShareLocal && is_file($albumShareLocal) && $siteRoot && str_starts_with($albumShareLocal, $siteRoot . DIRECTORY_SEPARATOR)) { $albumWhatsAppTarget = 'https://voleurdimages.fr/share-preview.php?p=' . rawurlencode($albumSharePath) . '&v=' . rawurlencode((string)(time() . '-' . random_int(100000, 999999))); } $albumWhatsAppShare = 'https://api.whatsapp.com/send?text=' . rawurlencode((string)($album['title'] ?? 'Reportage photo') . ' — ' . $albumWhatsAppTarget); ?><article class="story-card" data-category="<?= h(lower_fr($album['category'])) ?>" data-search="<?= h(lower_fr($album['title'].' '.$album['place'].' '.$album['description'])) ?>"><a href="<?= h($albumUrl) ?>" class="story-image" style="display:block;width:100%"><?php if ($album['cover']): ?><img src="<?= h($album['cover']) ?>" alt="<?= h($album['title']) ?>" loading="lazy"><?php else: ?><span class="no-image">V</span><?php endif; ?></a><div class="story-copy"><p class="eyebrow"><?= h($album['category'] ?: 'REPORTAGE') ?><?= $album['place'] ? ' · '.h($album['place']) : '' ?></p><h3><a href="<?= h($albumUrl) ?>"><?= h($album['title']) ?></a></h3><p><?= h($album['description'] ?: 'Un reportage photographique de Helis Denis.') ?></p><?php if (!empty($album['cover_caption'])): ?><p class="story-cover-comment"><strong><?= h((string)($album['cover_caption_title'] ?? '')) ?></strong> — <?= h((string)$album['cover_caption']) ?></p><?php endif; ?><div class="reportage-rating" data-reportage-rating data-album="<?= h($album['name']) ?>"><span class="reportage-rating-value">Notez ce reportage</span><div class="reportage-rating-stars" role="group" aria-label="Noter ce reportage sur 5"><?php for($star=1;$star<=5;$star++): ?><button type="button" data-rating-value="<?= $star ?>" aria-label="<?= $star ?> étoile<?= $star>1?'s':'' ?> sur 5" aria-pressed="false">☆</button><?php endfor; ?></div></div><a class="text-link" href="<?= h($albumUrl) ?>">Découvrir <b aria-hidden="true">↗</b></a><div class="share-actions story-share-actions" aria-label="Partager <?= h($album['title']) ?>"><a class="share-button share-whatsapp" href="<?= h($albumWhatsAppShare) ?>" target="_blank" rel="noopener noreferrer" aria-label="Partager <?= h($album['title']) ?> sur WhatsApp" title="Partager sur WhatsApp"><span aria-hidden="true">↗</span> WhatsApp</a></div></div></article><?php endforeach; ?>
<?php if (!$featured || ($featured['name'] ?? '') !== 'La Roche-Guyon'): $laRocheUrl = 'albums/La%20Roche-Guyon/index.html'; $laRocheWhatsAppTarget = 'https://voleurdimages.fr/share-preview.php?p=' . rawurlencode('/albums/La Roche-Guyon/index.html') . '&v=' . rawurlencode((string)(time() . '-' . random_int(100000, 999999))); $laRocheWhatsAppShare = 'https://api.whatsapp.com/send?text=' . rawurlencode('La Roche-Guyon — ' . $laRocheWhatsAppTarget); ?><article class="story-card" data-category="patrimoine" data-search="la roche-guyon val-d-oise vexin château seine village"><a href="<?= h($laRocheUrl) ?>" class="story-image" style="display:block;width:100%"><img src="albums/La%20Roche-Guyon/photos/la-roche-guyon-02.jpg" alt="Le château de La Roche-Guyon au-dessus du village" loading="lazy"></a><div class="story-copy"><p class="eyebrow">PATRIMOINE · VAL-D’OISE </p><h3><a href="<?= h($laRocheUrl) ?>">La Roche-Guyon</a></h3><p>Entre Seine et falaise, découvrez le château, le village, ses ruelles et les paysages du Vexin en huit photographies.</p><a class="text-link" href="<?= h($laRocheUrl) ?>">Découvrir <b aria-hidden="true">↗</b></a><div class="share-actions story-share-actions" aria-label="Partager La Roche-Guyon"><a class="share-button share-whatsapp" href="<?= h($laRocheWhatsAppShare) ?>" target="_blank" rel="noopener noreferrer" aria-label="Partager La Roche-Guyon sur WhatsApp" title="Partager sur WhatsApp"><span aria-hidden="true">↗</span> WhatsApp</a></div></div></article><?php endif; ?>
</div><p class="empty-state" id="empty-state" hidden>Aucun reportage ne correspond à cette recherche.</p></section>

<section class="about" id="auteur"><div class="about-number">HD</div><div><p class="eyebrow">DERRIÈRE L’OBJECTIF</p><h2>Au gré de mes visites</h2><p>Photographier, c’est garder la trace d’un lieu, d’une lumière ou d’un instant. Je vous invite à découvrir mes balades en Charente, en Charente-Maritime et ailleurs, racontées en images.</p><p class="signature">Helis Denis <span>— Voleur d’images</span></p></div><a class="about-link" href="https://clicetdecouvertes.fr/" target="_blank" rel="noopener">Clic &amp; Découvertes ↗</a></section>
</main><a class="guestbook-float" href="livre-or.php" aria-label="Ouvrir le livre d’or et laisser un message">Livre d’or <span>— laissez-nous un message !</span></a><footer><a class="brand footer-brand" href="index.php"><span class="brand-mark">V</span><span>VOLEUR D’IMAGES<small>REPORTAGES PHOTO</small></span></a><p>Création et hébergement Helis Denis</p><p>© <?= date('Y') ?> Helis Denis · Tous droits réservés</p></footer>
<script src="/assets/livre-or-flottant.js" defer></script><script src="assets/reportage.js" defer></script>
<script>document.querySelector('[data-home-whatsapp-share]')?.addEventListener('click',function(){var page=new URL(this.dataset.homeUrl,window.location.origin);page.searchParams.set('partage',Date.now()+'-'+Math.random().toString(36).slice(2,8));this.href='https://api.whatsapp.com/send?text='+encodeURIComponent('Voleur d’images — '+page.href);});document.querySelector('[data-home-facebook-share]')?.addEventListener('click',function(){var page=new URL(this.dataset.homeUrl,window.location.origin);page.searchParams.set('partage',Date.now()+'-'+Math.random().toString(36).slice(2,8));this.href='https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(page.href);});</script></body></html>
