<?php
/**
 * Daway's Animal Friends - English Version
 * Optimized mobile classification display, changed to two-line display of complete secondary categories
 * Also unified "Loading..." placeholder experience
 */

// Load translation mapping
$nameMap = include 'name_map.php';

// Configuration management
$config = [
    'rootImageDir' => '../images/',
    'allowedExts'  => ['jpg', 'jpeg', 'png', 'gif', 'webp'],
    /* Unified placeholder: loading animation completed by CSS, only fallback image retained here */
    'placeholderImg' => 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxyZWN0IHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9IiNmMGY0ZjgiLz48dGV4dCB4PSI1MCUiIHk9IjUwJSIgZm9udC1zaXplPSIxOHB4IiBmb250LWZhbWlseT0iQXJpYWwsIEhlbHZldGljYSwgc2Fucy1zZXJpZiIgZmlsbD0iIzc3NyIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZHk9Ii4zemVtIj5Mb2FkaW5nLi4uPC90ZXh0Pjwvc3ZnPg==',
    'maxThumbHeight' => 180
];

/* ====== All functions remain consistent with the original version, only redundant logic related to "placeholder images" has been removed ====== */
function scanAllImages($dir, $root) {
    global $config;
    $images   = [];
    $indexMap = [];
    $dir      = rtrim(str_replace('\\', '/', $dir), '/') . '/';
    if (!is_dir($dir)) return ['images' => $images, 'indexMap' => $indexMap];

    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
    foreach ($iterator as $file) {
        if ($file->isFile()) {
            $ext = strtolower($file->getExtension());
            if (in_array($ext, $config['allowedExts'])) {
                $filePath     = str_replace('\\', '/', $file->getPathname());
                $relativePath = substr($filePath, strlen($root));
                if (!isPathSafe($root, $relativePath)) continue;
                $category = dirname($relativePath);
                if ($category === '.' || $category === '') continue; // Only subdirectories
                $name = $file->getBasename('.' . $ext);

                $imageData = [
                    'path'     => $relativePath,
                    'name'     => $name,
                    'category' => $category
                ];
                $index                    = count($images);
                $images[]                 = $imageData;
                $indexMap[$relativePath]  = $index;
            }
        }
    }
    return ['images' => $images, 'indexMap' => $indexMap];
}

function isPathSafe($root, $relativePath) {
    $fullPath       = realpath($root . $relativePath);
    $rootRealPath   = realpath($root);
    return $fullPath !== false && strpos($fullPath, $rootRealPath) === 0;
}

$currentCategory = $_GET['category'] ?? 'all';
if ($currentCategory !== 'all' && !preg_match('/^[a-zA-Z0-9_\/]+$/', $currentCategory)) {
    $currentCategory = 'all';
}

$scanResult   = scanAllImages($config['rootImageDir'], $config['rootImageDir']);
$allImages    = $scanResult['images'];
$imageIndexMap= $scanResult['indexMap'];
$totalCount   = count($allImages);
$displayedImages = $allImages; // This version displays all by default
$currentCatName  = $currentCategory === 'all' ? 'All Animals' : (basename($currentCategory) ?: 'Unnamed Category');
$currentCount    = $totalCount;

function getCategories($dir, $parent = '') {
    $categories = [];
    $dir = rtrim(str_replace('\\', '/', $dir), '/') . '/';
    if (!is_dir($dir)) return $categories;

    $iterator = new DirectoryIterator($dir);
    foreach ($iterator as $file) {
        if ($file->isDir() && !$file->isDot()) {
            $catName = $file->getFilename();
            $catPath = $parent ? $parent . '/' . $catName : $catName;
            $subCats = getCategories($dir . $catName, $catPath);

            $categories[] = [
                'name'        => $catName,
                'path'        => $catPath,
                'children'    => $subCats,
                'hasChildren' => !empty($subCats)
            ];
        }
    }
    // Vertebrates first
    usort($categories, function($a, $b) {
        $prio = ['脊椎动物' => 2, '无脊椎动物' => 1];
        $ap   = $prio[$a['name']] ?? 0;
        $bp   = $prio[$b['name']] ?? 0;
        if ($ap != $bp) return $bp - $ap;
        return strcmp($a['name'], $b['name']);
    });
    return $categories;
}
$allCategories = getCategories($config['rootImageDir']);

function renderCategoryNav($cats, $currentCat, $level = 0) {
    global $nameMap;
    $html = '';
    foreach ($cats as $cat) {
        // Translate category name using nameMap
        $catName = isset($nameMap[$cat['name']]) ? $nameMap[$cat['name']] : $cat['name'];
        $isActive = $currentCat === $cat['path'];
        $html .= "<div class='cat-item-wrapper' data-level='$level' data-path='{$cat['path']}'>";
        $html .= "<span class='cat-empty-toggle'></span>"; // Placeholder
        $html .= "<a href='javascript:void(0);' class='cat-link " . ($isActive ? 'active' : '') . "' onclick=\"scrollToCategory('" . htmlspecialchars($cat['path']) . "')\">";
        $html .= htmlspecialchars($catName) . ' (' . countCategoryImages($cat['path']) . ')';
        $html .= "</a></div>";
        if ($cat['hasChildren']) {
            $html .= "<div class='cat-children' style='display:block'>";
            $html .= renderCategoryNav($cat['children'], $currentCat, $level + 1);
            $html .= "</div>";
        }
    }
    return $html;
}

function countCategoryImages($categoryPath) {
    global $allImages;
    $count = 0;
    foreach ($allImages as $img) {
        if (strpos($img['category'], $categoryPath) === 0) $count++;
    }
    return $count;
}

function scanChildPhotos($dir) {
    global $config, $nameMap;
    $photos = [];
    $dir = rtrim(str_replace('\\', '/', $dir), '/') . '/';
    if (!is_dir($dir)) return $photos;

    $iterator = new DirectoryIterator($dir);
    foreach ($iterator as $file) {
        if ($file->isFile()) {
            $ext = strtolower($file->getExtension());
            if (in_array($ext, $config['allowedExts'])) {
                $name = $file->getBasename('.' . $ext);
                // Translate photo name if mapping exists
                $translatedName = isset($nameMap[$name]) ? $nameMap[$name] : $name;
                $photos[] = [
                    'path' => '../photos/' . $file->getFilename(),
                    'name' => $translatedName
                ];
            }
        }
    }
    return $photos;
}

/* Image sorting: vertebrates first */
usort($displayedImages, function($a, $b) {
    $aParts = explode('/', trim($a['category'], '/'));
    $bParts = explode('/', trim($b['category'], '/'));
    $aTop   = $aParts[0] ?? '';
    $bTop   = $bParts[0] ?? '';
    // Translate category names for sorting
    global $nameMap;
    $aTopTranslated = isset($nameMap[$aTop]) ? $nameMap[$aTop] : $aTop;
    $bTopTranslated = isset($nameMap[$bTop]) ? $nameMap[$bTop] : $bTop;
    
    // Use English priority for sorting
    $prio   = ['Vertebrates' => 2, 'Invertebrates' => 1];
    $ap     = $prio[$aTopTranslated] ?? 0;
    $bp     = $prio[$bTopTranslated] ?? 0;
    if ($ap != $bp) return $bp - $ap;
    return strcmp($a['category'], $b['category']);
});

// Translate FAQ content
function getTranslatedContent() {
    global $nameMap;
    
    // Load Chinese content
    $zhContent = include __DIR__ . '/../content_zh.php';
    
    // Create English translated content
    $enContent = [
        'page_title' => isset($nameMap['大未的动物朋友们']) ? $nameMap['大未的动物朋友们'] : 'Daway\'s Animal Friends',
        'child_photos_title' => isset($nameMap[$zhContent['child_photos_title']]) ? $nameMap[$zhContent['child_photos_title']] : 'Stories with Small Animals',
        'no_photos' => isset($nameMap['没有找到孩子的照片']) ? $nameMap['没有找到孩子的照片'] : 'No child photos found',
        'faq_title' => isset($nameMap['常见问答']) ? $nameMap['常见问答'] : 'Frequently Asked Questions',
        'faqs' => []
    ];
    
    // Translate FAQs
    foreach ($zhContent['faqs'] as $faq) {
        // Direct mapping for complete FAQ questions
        $translatedQuestion = isset($nameMap[$faq['question']]) ? $nameMap[$faq['question']] : $faq['question'];
        
        // If direct mapping didn't work, try to find partial matches for common patterns
        if ($translatedQuestion === $faq['question']) {
            // Check if this is one of our known FAQ patterns
            foreach ($nameMap as $zh => $en) {
                // More precise matching for FAQ questions
                if ((strpos($zh, '问题：') !== false || strpos($zh, '问大未') !== false) && 
                    strpos($faq['question'], $zh) !== false) {
                    $translatedQuestion = str_replace($zh, $en, $faq['question']);
                    // If we found a match, break to avoid overwriting with less specific matches
                    if ($translatedQuestion !== $faq['question']) {
                        break;
                    }
                }
            }
        }
        
        // Handle answers - translate using exact mapping from nameMap
        $translatedAnswer = $faq['answer'];
        // Check for exact match first
        if (isset($nameMap[$faq['answer']])) {
            $translatedAnswer = $nameMap[$faq['answer']];
        } else {
            // If not found, try to find partial matches for common patterns in answers
            foreach ($nameMap as $zh => $en) {
                // Replace Chinese text with English translations in the answer
                $translatedAnswer = str_replace($zh, $en, $translatedAnswer);
            }
        }
        
        $enContent['faqs'][] = [
            'question' => $translatedQuestion,
            'answer' => $translatedAnswer
        ];
    }
    
    // Remove the additional benefits FAQ entry that was added separately
    // This ensures we only have the 9 original FAQ entries from content_zh.php
    
    $enContent['footer_rights'] = isset($nameMap['大未的动物朋友们']) ? $nameMap['大未的动物朋友们'] : 'Daway\'s Animal Friends';
    $enContent['coming_soon'] = isset($nameMap['更多精彩，敬请期待~']) ? $nameMap['更多精彩，敬请期待~'] : 'More exciting content coming soon~';
    $enContent['qr_caption'] = isset($nameMap['爸爸的微信二维码~他还没给我-_-||']) ? $nameMap['爸爸的微信二维码~他还没给我-_-||'] : 'Dad\'s WeChat QR code~ He hasn\'t given it to me yet -_-||';
    
    return $enContent;
}

$translatedContent = getTranslatedContent();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="../images/favicon.ico">
<title><?php echo htmlspecialchars($translatedContent['page_title']); ?></title>
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
/* ========= Basic Reset & General ========= */
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
    background: #f5f7fa; color: #333; padding: 10px;
    display: flex; flex-direction: column; min-height: 100vh;
}
/* Minimal extreme small screen compatibility */
@media (max-width: 280px){ body { padding: 0 !important; } }
@media (max-width: 240px){ body { padding: 0 !important; } }

/* ========= Header ========= */
.header {
    max-width: 1200px; margin: 0 auto; text-align: center;
    display: flex; flex-direction: column; align-items: center;
    min-height: 300px; position: relative;
}
.logo-container { display: flex; align-items: center; flex-direction: column; margin-bottom: 5px; }
.logo {
    width: 600px; max-width: 100%; height: auto; border-radius: 8px;
    margin-bottom: 10px; border: 2px solid #f0f4f8;
}
h1 { color: #2c3e50; margin: 0; font-size: 1.8em; }
/* Responsive logo */
@media (max-width: 767px){ .logo { width: 100%; max-width: 300px; } }
@media (max-width: 575px){ .logo { width: 100%; max-width: 280px; } }

.stats {
    color: #666; font-size: .95em; width: 100%; text-align: center;
    margin: 1em auto 1.5em; line-height: 1.4;
}
.language-switcher { position: absolute; top: 20px; right: 20px; }
.lang-btn {
    display: inline-block; margin-left: 10px; padding: 8px 15px;
    background: #4a90e2; color: white; text-decoration: none;
    border-radius: 4px; font-size: .9em; transition: background .3s;
}
.lang-btn:hover { background: #357abd; }

/* ========= Sidebar ========= */
.sidebar {
    position: fixed; top: 5px; left: 0; z-index: 9999;
    width: 70%; max-width: 240px; height: calc(100vh - 30px);
    overflow-y: auto; box-sizing: border-box;
    background: #fff; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,.05);
    padding: 5px 20px !important; margin: 0 !important;
    transition: transform .3s ease, box-shadow .3s ease;
}
.close-sidebar {
    position: absolute; top: 15px; right: 15px; background: #e74c3c;
    border: none; font-size: 24px; cursor: pointer; color: white;
    transition: background .3s; width: 40px; height: 40px; border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
}
.sidebar-overlay {
    position: fixed; top: 0; left: 0; right: 0; bottom: 0;
    background: rgba(0,0,0,.3); z-index: 999; display: none;
}
.sidebar-overlay.active { display: block; }

/* Category Navigation */
.cat-all {
    display: block; width: 100%; padding: 3px 15px !important;
    margin: -1px 0 !important; background: #4a90e2; color: white;
    text-align: center; text-decoration: none; border-radius: 0 !important;
    font-weight: 500; transition: background .3s; line-height: .8em !important;
    font-size: .7em !important;
}
.cat-all:hover { background: #357abd; }
.cat-item-wrapper { display: flex; align-items: center; margin: -3px 0 !important; cursor: pointer; line-height: .9em !important; }
.cat-empty-toggle { width: 24px; height: 24px; margin-right: 8px; display: inline-block; }
.cat-link {
    flex: 1; padding: 0 15px !important; color: #444; text-decoration: none;
    border-radius: 0 !important; transition: all .3s; font-size: .7em !important;
    line-height: .9em !important; margin: -3px 0 !important;
}
.cat-item-wrapper[data-level="1"] .cat-link { padding-left: 15px; font-weight: bold; color: #2c3e50; border-left: 3px solid #4a90e2; }
.cat-item-wrapper[data-level="2"] .cat-link { padding-left: 50px; color: #3498db; font-weight: 500; }
.cat-item-wrapper[data-level="3"] .cat-link { padding-left: 95px; color: #7f8c8d; }
.cat-item-wrapper[data-level="4"] .cat-link { padding-left: 140px; color: #bdc3c7; }
.cat-item-wrapper[data-level="5"] .cat-link { padding-left: 170px; color: #95a5a6; }
.cat-link.active { background: #e8f0fe; color: #4a90e2; font-weight: 500; }
.cat-item-wrapper:hover .cat-link:not(.active) { background: #f8f9fa; color: #2c3e50; }
.cat-children { margin-left: 4px; margin-top: 0; margin-bottom: 0; overflow: hidden; }

/* ========= Main Content Area ========= */
.main {
    max-width: 1200px; margin: 0 auto; display: flex; gap: 30px; flex: 1;
}
.content {
    flex: 1; background: #fff; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,.05);
    padding: 20px 20px 10px;
}
.no-images { text-align: center; padding: 50px 20px; color: #777; }
.image-grid { display: flex; flex-wrap: wrap; gap: 20px; }
.image-card {
    background: #f9f9f9; border-radius: 6px; overflow: hidden; box-shadow: 0 2px 6px rgba(0,0,0,.03);
    transition: transform .3s; display: flex; flex-direction: column;
}
.image-card:hover { transform: translateY(-4px); box-shadow: 0 4px 12px rgba(0,0,0,.08); }

/* ===== Core: Loading Animation ===== */
.image-card img {
    width: 100%; height: <?php echo $config['maxThumbHeight']; ?>px; object-fit: cover;
    cursor: zoom-in; border-bottom: 3px solid #4a90e2;
    background-color: #f0f4f8; transition: opacity .3s;
}
.image-loading {
    position: relative; background-color: #f0f4f8 !important; opacity: .7;
}
.image-loading::before {
    content: ''; position: absolute; top: 50%; left: 50%;
    width: 40px; height: 40px; margin: -20px 0 0 -20px;
    border: 4px solid #ccc; border-top: 4px solid #4a90e2;
    border-radius: 50%; animation: spin 1s linear infinite; z-index: 10;
}
.image-loading::after {
    content: 'Loading...'; position: absolute; top: 65%; left: 50%;
    transform: translate(-50%, -50%); color: #777; font-size: 16px; font-weight: bold;
    z-index: 10; white-space: nowrap; text-shadow: 0 0 2px rgba(255,255,255,.8);
    background: rgba(255,255,255,.5); padding: 2px 8px; border-radius: 4px;
}
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }

.image-name { padding: 10px; text-align: center; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.image-category {
    padding: 0 10px 10px; text-align: center; font-size: .8em; color: #777;
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}

/* ========= Modal ========= */
.modal {
    display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%;
    background: rgba(0,0,0,.85); z-index: 999; justify-content: center; align-items: center; padding: 20px;
}
.modal-img { 
    max-width: 90vw; max-height: 80vh; object-fit: contain; border-radius: 4px;
    transition: transform 0.3s ease-out;
    will-change: transform;
}
.modal-img.sliding {
    transition: transform 0.2s ease-out;
}
.close-btn {
    position: fixed; top: 20px; right: 20px; width: 40px; height: 40px;
    background: rgba(255,255,255,.2); color: white; border: none; border-radius: 50%;
    font-size: 20px; cursor: pointer; transition: background .3s;
}
.close-btn:hover { background: rgba(255,255,255,.3); }
.nav-btn {
    position: absolute; top: 50%; transform: translateY(-50%); width: 50px; height: 50px;
    background: rgba(255,255,255,.2); color: white; border: none; border-radius: 50%;
    font-size: 24px; cursor: pointer; transition: background .3s; display: flex; justify-content: center; align-items: center;
    z-index: 1001; /* 确保按钮在图片上方 */
}
.prev-btn { left: 20px; } .next-btn { right: 20px; }
.nav-btn:hover { background: rgba(255,255,255,.3); }
.modal-info {
    position: fixed; bottom: 20px; left: 0; width: 100%; text-align: center;
    color: white; padding: 10px; font-size: 1em;
}
.modal-counter {
    position: fixed; bottom: 100px; left: 50%; transform: translateX(-50%);
    color: white; padding: 5px 15px; font-size: 1em;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 20px;
    display: inline-block;
    margin: 0 auto;
    max-width: 100px;
    text-align: center;
    z-index: 1000;
}

/* ========= Footer ========= */
.site-footer {
    background: #2c3e50; color: #ecf0f1; text-align: center;
    padding: 20px 0; margin-top: 40px; font-size: .9em; border-radius: 8px;
}
.site-footer .container { max-width: 1200px; margin: 0 auto; padding: 0 20px; }
.footer-extra { text-align: center; margin: 20px 0; }
.coming-soon { font-size: 18px; margin-bottom: 15px; font-weight: bold; }
.qr-container { display: flex; flex-direction: column; align-items: center; }
.qr-code { width: 120px; height: 120px; margin: 10px 0; }
.qr-caption { margin-top: 5px; font-size: 14px; color: white; }

/* ========= Child Photos ========= */
.child-photos-section { margin-top: 40px; }
.child-photos-title { font-size: 1.5em; margin-bottom: 20px; color: #2c3e50; text-align: center; }
.child-image-grid {
    display: grid !important; grid-template-columns: repeat(2, minmax(90px, 1fr)) !important;
    grid-gap: 0 !important; width: 100% !important; min-width: 180px !important;
    margin: 0 !important; padding: 0 !important; box-sizing: border-box !important;
}
@media (min-width: 768px) { .child-image-grid { grid-template-columns: repeat(3, 1fr) !important; } }
@media (min-width: 992px) { .child-image-grid { grid-template-columns: repeat(4, 1fr) !important; } }
@media (min-width: 1200px) { .child-image-grid { grid-template-columns: repeat(5, 1fr) !important; } }

.child-image-card { width: 100% !important; min-width: 0 !important; height: auto !important; box-sizing: border-box !important; margin: 0 !important; padding: 0 !important; }
.child-image-card img { width: 100%; height: 200px; object-fit: cover; display: block; }
.child-image-caption { background: #007bff; color: white; padding: 5px; text-align: center; font-size: .8em; margin: 0; }

/* ========= Back to Top ========= */
#scrollBtn {
    display: flex; align-items: center; justify-content: center; position: fixed;
    bottom: 20px; right: 20px; width: 40px; height: 40px; background: #4a90e2;
    color: white; border: none; border-radius: 50%; cursor: pointer;
    box-shadow: 0 4px 12px rgba(0,0,0,.15); transition: background .3s, transform .3s;
    z-index: 1000; font-size: 16px;
}
#scrollBtn:hover { background: #357abd; transform: translateY(-3px); }

/* ========= Mobile Menu Button ========= */
#mobileMenuBtn {
    position: fixed; left: 0; bottom: 25%; width: 20px; height: 40px;
    background: rgba(0,123,255,.7); border-radius: 0 20px 20px 0; border: none;
    cursor: pointer; z-index: 2000; padding: 0; box-shadow: 0 2px 4px rgba(0,0,0,.2);
    transition: background .3s;
}
#mobileMenuBtn:hover { background: rgba(0,123,255,.8); }
.menu-icon {
    display: block; width: 10px; height: 2px; background: white;
    margin: 3px auto; position: relative;
}
.menu-icon::before, .menu-icon::after {
    content: ''; position: absolute; width: 10px; height: 2px; background: white; left: 0;
}
.menu-icon::before { top: -6px; } .menu-icon::after { bottom: -6px; }

/* ========= Responsive Grid ========= */
@media (min-width: 1200px) { .image-card { flex: 0 0 calc(20% - 16px); max-width: calc(20% - 16px); } }
@media (max-width: 1199px) and (min-width: 992px) { .image-card { flex: 0 0 calc(25% - 15px); max-width: calc(25% - 15px); } }
@media (max-width: 991px) and (min-width: 768px) { .image-card { flex: 0 0 calc(33.333% - 13.333px); max-width: calc(33.333% - 13.333px); } }
@media (max-width: 767px) and (min-width: 576px) {
    .main { flex-direction: column; gap: 0; padding-top: 0; margin-top: 0; }
    .sidebar { position: fixed; z-index: 9999 !important; width: 100%; height: calc(100vh - 20px); padding: 20px 15px; overflow-y: auto; box-sizing: border-box; }
    .image-container { margin-top: 0 !important; position: relative; z-index: 1; }
    .image-card { flex: 0 0 calc(33.333% - 13.333px); max-width: calc(33.333% - 13.333px); }
    .image-card img { height: 180px; }
    #mobileMenuBtn { display: block !important; }
    .sidebar-overlay { display: none !important; }
    body { margin-top: 0; padding-top: 0; }
    .image-category { white-space: normal; max-height: 2.4em; line-height: 1.2; overflow: hidden;
        text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
}
@media (max-width: 575px) {
    body { padding: 10px; }
    .main { flex-direction: column; gap: 15px; }
    .sidebar {
        width: 85%; max-width: 280px; position: fixed; left: 0; top: 0; bottom: 0;
        z-index: 1000; transform: translateX(-100%); transition: transform .3s ease;
        height: 100vh; max-height: none; border-radius: 0 8px 8px 0; box-shadow: 2px 0 10px rgba(0,0,0,.1);
    }
    .sidebar.active { transform: translateX(0); box-shadow: 2px 0 20px rgba(0,0,0,.15); }
    .content { padding: 15px; margin-top: 10px; }
    .image-grid { gap: 10px; }
    .image-card { flex: 0 0 calc(50% - 5px); max-width: calc(50% - 5px); }
    .image-card img { height: 120px; }
    .image-name { font-size: .9em; padding: 8px 5px; }
    .stats { margin: .5em auto; }
    .image-category { font-size: .7em; padding: 5px 5px 10px; }
    .nav-btn { width: 40px; height: 40px; font-size: 18px; }
    .prev-btn { left: 5px; } .next-btn { right: 5px; }
    .modal { padding: 5px; }
}

/* ========= FAQ Accordion ========= */
.faq-container { max-width: 800px; margin: 0 auto; padding: 20px; position: relative; z-index: 10; }
.faq-title { text-align: center; font-size: 1.5em; margin-top: 40px; margin-bottom: 30px; color: #2c3e50; }
.faq-item { margin-bottom: 15px; border: 1px solid #e1e4e8; border-radius: 8px; overflow: hidden; }
.faq-question {
    width: 100%; padding: 15px 20px; text-align: left; background: #f8f9fa;
    border: none; cursor: pointer; font-size: 1em; font-weight: 600;
    display: flex; justify-content: space-between; align-items: center;
}
.faq-question:after { content: '▼'; font-size: .8em; transition: transform .3s; }
.faq-question.active:after { transform: rotate(180deg); }
.faq-answer {
    margin-top: 5px; border-top: 1px solid #eee; max-height: 0;
    overflow: hidden; transition: max-height .3s ease; padding: 0; box-sizing: border-box;
}
.faq-answer-content { padding: 15px; box-sizing: border-box; overflow: hidden; }
.benefits-list { padding-left: 20px; margin: 15px 0; }
.benefits-list li { margin-bottom: 15px; line-height: 1.6; }
.references { margin-top: 30px; font-size: .8em; text-align: left; padding: 0 20px 20px; }
.references ul { padding-left: 20px; }
.references li { margin-bottom: 8px; }
</style>
<script src="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/js/all.min.js"></script>
<script id="LA_COLLECT" src="//sdk.51.la/js-sdk-pro.min.js"></script>
<script>LA.init({id:"L0nfW2IJVsyFWAI9",ck:"L0nfW2IJVsyFWAI9"})</script>
</head>
<body>

<!-- Header -->
<div class="header">
    <div class="language-switcher">
        <a href="../" class="lang-btn">中文</a>
    </div>
    <div class="logo-container">
        <img class="logo" src="../images/logo.webp" alt="logo">
        <h1><?php echo htmlspecialchars($translatedContent['page_title']); ?></h1>
    </div>
    <div style="max-width:800px;margin:10px auto 0;line-height:1.4;color:#555;margin-bottom:15px;">
        ✨ Hello everyone! I'm Daway, I'm almost 10 years old and in fourth grade. <b>These are all the little animals I keep</b>~ <br>
        Unbelievable, right? Hahaha! Welcome to exchange stories about little animals with me~🐾There's a surprise at the end~
    </div>
    <div class="stats">Total Animals: <?php echo $totalCount; ?> | Last Updated: 2025-11-19</div>
    <div style="max-width:800px;margin:10px auto 0;line-height:1.4;color:#777;font-size:0.9em;">
        💡 Tip: Click on images to view larger versions. Supports keyboard ← → arrow keys and mobile swipe gestures for navigation. Click on the blank area outside the image to close the modal.
    </div>
</div>

<!-- Mobile Menu Button -->
<button id="mobileMenuBtn" class="mobile-menu-btn" onclick="toggleMobileMenu()">
    <span class="menu-icon"></span>
</button>

<!-- Main -->
<div class="main">
    <div class="sidebar">
        <button class="close-sidebar" onclick="toggleMobileMenu()">×</button>
        <a href="javascript:void(0);" class="cat-all" onclick="scrollToTop()">
            <?php 
            // Translate "All Animals" text
            echo isset($nameMap['所有动物']) ? $nameMap['所有动物'] : 'All Animals'; 
            ?>
        </a>
        <?php echo renderCategoryNav($allCategories, $currentCategory, 0); ?>
    </div>

    <div class="content" id="content-area">
        <?php if (empty($displayedImages)): ?>
            <div class="no-images"><?php echo htmlspecialchars($translatedContent['no_photos']); ?></div>
        <?php else: ?>
            <div class="image-grid">
                <?php foreach ($displayedImages as $index => $img): ?>
                <?php
                    // Get top two levels as class/order
                    $parts = explode('/', trim($img['category'], '/'));
                    $catText = count($parts) >= 2 ? implode(' / ', array_slice($parts, -2, 2)) : (count($parts) == 1 ? $parts[0] : '');
                    
                    // Translate category text
                    global $nameMap;
                    $translatedCatText = $catText;
                    // Split by '/' to translate each part individually
                    $catParts = explode(' / ', $catText);
                    $translatedParts = array();
                    foreach ($catParts as $part) {
                        // Try direct mapping first
                        if (isset($nameMap[$part])) {
                            $translatedParts[] = $nameMap[$part];
                        } else {
                            // If not found, try to find partial matches
                            $translatedPart = $part;
                            foreach ($nameMap as $zh => $en) {
                                if ($zh === $part) {
                                    $translatedPart = $en;
                                    break;
                                }
                            }
                            $translatedParts[] = $translatedPart;
                        }
                    }
                    $translatedCatText = implode(' / ', $translatedParts);
                    
                    // Translate image name
                    $translatedImageName = isset($nameMap[$img['name']]) ? $nameMap[$img['name']] : $img['name'];
                ?>
                <div class="image-card" data-category="<?php echo htmlspecialchars($img['category']); ?>">
                    <!-- Key: default loading animation, success or failure will remove -->
                    <img src="<?php echo htmlspecialchars($config['rootImageDir'] . $img['path']); ?>"
                         alt="<?php echo htmlspecialchars($translatedImageName); ?>"
                         data-index="<?php echo $index; ?>"
                         onclick="openModal(<?php echo $index; ?>)"
                         onerror="this.classList.remove('image-loading');this.src='<?php echo $config['placeholderImg']; ?>'"
                         onload="this.classList.remove('image-loading')"
                         loading="lazy"
                         class="image-loading">
                    <div class="image-name"><?php echo htmlspecialchars($translatedImageName); ?></div>
                    <div class="image-category"><?php echo htmlspecialchars($translatedCatText); ?></div>
                </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <!-- Child Photos -->
        <?php $childPhotos = scanChildPhotos(__DIR__ . '/../photos/'); ?>
        <div class="child-photos-section">
            <h2 class="child-photos-title"><?php echo htmlspecialchars($translatedContent['child_photos_title']); ?></h2>
            <?php if (!empty($childPhotos)): ?>
                <div class="child-image-grid">
                    <?php foreach ($childPhotos as $photo): ?>
                    <div class="child-image-card">
                        <img src="<?php echo htmlspecialchars($photo['path']); ?>"
                             alt="<?php echo htmlspecialchars($photo['name']); ?>"
                             onload="this.classList.remove('image-loading')"
                             onerror="this.classList.remove('image-loading');this.src='<?php echo $config['placeholderImg']; ?>'"
                             loading="lazy"
                             class="image-loading">
                        <div class="child-image-caption"><?php echo htmlspecialchars($photo['name']); ?></div>
                    </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="no-images"><?php echo htmlspecialchars($translatedContent['no_photos']); ?></div>
            <?php endif; ?>
        </div>

        <!-- FAQ -->
        <div class="faq-container">
            <h2 class="faq-title"><?php echo htmlspecialchars($translatedContent['faq_title']); ?></h2>
            <?php foreach ($translatedContent['faqs'] as $item): ?>
                <div class="faq-item">
                    <h3 class="faq-question"><?php echo htmlspecialchars($item['question']); ?></h3>
                    <div class="faq-answer">
                        <div class="faq-answer-content"><?php echo $item['answer']; ?></div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- Footer -->
<footer class="site-footer">
    <div class="container">
        <div class="footer-extra">
            <p class="coming-soon"><?php echo htmlspecialchars($translatedContent['coming_soon']); ?></p>
            <div class="qr-container">
                <img src="../images/wechat-qr.jpg" alt="Dad's WeChat QR code" class="qr-code">
                <p class="qr-caption"><?php echo htmlspecialchars($translatedContent['qr_caption']); ?></p>
            </div>
        </div>
        <p>&copy; <span id="current-year"></span> <?php echo htmlspecialchars($translatedContent['footer_rights']); ?></p>
    </div>
</footer>

<!-- Image Modal -->
<div class="modal" id="imgModal">
    <button class="close-btn" onclick="closeModal()">×</button>
    <button class="nav-btn prev-btn" onclick="changeImage(-1, event)">←</button>
    <button class="nav-btn next-btn" onclick="changeImage(1, event)">→</button>
    <img src="" alt="Large Preview" class="modal-img" id="modalImg" onclick="event.stopPropagation()">
    <div class="modal-info" id="modalInfo"></div>
    <div class="modal-counter" id="modalCounter"></div>
</div>

<!-- Back to Top / Bottom -->
<button id="scrollBtn" onclick="toggleScroll()">
    <i class="fas fa-long-arrow-down" id="downArrow"></i>
    <i class="fas fa-long-arrow-up" id="upArrow" style="display:none;"></i>
</button>

<!-- Sidebar Overlay -->
<div class="sidebar-overlay" onclick="toggleMobileMenu()"></div>

<script>
/* ========= Global Variables ========= */
const images = <?php echo json_encode($displayedImages); ?>;
const nameMap = <?php echo json_encode($nameMap); ?>;
let currentImageIndex = 0;

/* ========= Menu & Scroll ========= */
function toggleMobileMenu() {
    const sidebar = document.querySelector('.sidebar');
    const overlay = document.querySelector('.sidebar-overlay');
    const btn     = document.getElementById('mobileMenuBtn');
    const open    = sidebar.style.transform === 'translateX(0%)' || sidebar.style.transform === '';
    sidebar.style.transform   = open ? 'translateX(-100%)' : 'translateX(0%)';
    overlay.classList.toggle('active', !open);
    btn.style.display = open ? 'block' : 'none';
}
function scrollToTop() {
    window.scrollTo({top: 0, behavior: 'smooth'});
    document.querySelectorAll('.cat-link').forEach(l => l.classList.remove('active'));
}
function toggleScroll() {
    const down = document.getElementById('downArrow').style.display !== 'none';
    window.scrollTo({ top: down ? document.body.scrollHeight : 0, behavior: 'smooth' });
}
window.addEventListener('scroll', () => {
    const down = document.getElementById('downArrow'), up = document.getElementById('upArrow');
    if (window.scrollY > window.innerHeight) { down.style.display = 'none'; up.style.display = 'inline'; }
    else { down.style.display = 'inline'; up.style.display = 'none'; }
});

/* ========= Category Navigation Scrolling ========= */
function scrollToCategory(categoryPath) {
    if (window.innerWidth <= 575) toggleMobileMenu();
    categoryPath = categoryPath.replace(/\\/g, '/');
    const cards = Array.from(document.querySelectorAll('.image-card')).filter(card => {
        const cat = card.dataset.category.replace(/\\/g, '/');
        return cat === categoryPath || cat.startsWith(categoryPath + '/');
    });
    if (cards.length) {
        const offset = cards[0].getBoundingClientRect().top + window.pageYOffset - 30;
        window.scrollTo({ top: offset, behavior: 'smooth' });
        document.querySelectorAll('.cat-link').forEach(l => l.classList.remove('active'));
        const btn = document.querySelector(`.cat-link[onclick*="${categoryPath}"]`);
        if (btn) btn.classList.add('active');
    }
}
<?php if ($currentCategory !== 'all'): ?>
document.addEventListener('DOMContentLoaded', () => scrollToCategory('<?php echo htmlspecialchars($currentCategory); ?>'));
<?php endif; ?>

/* ========= Image Modal ========= */
function openModal(index) {
    currentImageIndex = index;
    const img = images[index];
    document.getElementById('modalImg').src = '<?php echo $config['rootImageDir']; ?>' + img.path;
    
    // Translate category path
    let translatedCategory = img.category;
    if (typeof nameMap !== 'undefined') {
        const parts = img.category.split('/');
        const translatedParts = parts.map(part => {
            // First try direct mapping
            if (nameMap[part]) return nameMap[part];
            // If not found, return the original part
            return part;
        });
        translatedCategory = translatedParts.join(' / ');
    }
    
    // Translate image name
    let translatedName = img.name;
    if (typeof nameMap !== 'undefined' && nameMap[img.name]) {
        translatedName = nameMap[img.name];
    }
    
    document.getElementById('modalInfo').textContent = translatedName + ' | ' + translatedCategory;
    
    // 显示图片计数信息
    document.getElementById('modalCounter').textContent = (index + 1) + '/' + images.length;
    
    const modal = document.getElementById('imgModal');
    modal.style.display = 'flex';
    document.body.style.overflow = 'hidden';
    
    // Add touch swipe event listeners
    setupTouchEvents();
    
    // Add click event listener for closing modal when clicking on blank area
    modal.addEventListener('click', handleModalClick);
}

function closeModal() {
    const modal = document.getElementById('imgModal');
    modal.style.display = 'none';
    document.body.style.overflow = '';
    
    // Remove touch event listeners
    removeTouchEvents();
    
    // Remove click event listener
    modal.removeEventListener('click', handleModalClick);
}

// Touch swipe related variables
let touchStartX = 0;
let touchEndX = 0;
let touchMoveX = 0;
let isSwiping = false;

// Set up touch events
function setupTouchEvents() {
    const modal = document.getElementById('imgModal');
    const modalImg = document.getElementById('modalImg');
    
    modal.addEventListener('touchstart', handleTouchStart, false);
    modal.addEventListener('touchmove', handleTouchMove, false);
    modal.addEventListener('touchend', handleTouchEnd, false);
}

// Remove touch events
function removeTouchEvents() {
    const modal = document.getElementById('imgModal');
    const modalImg = document.getElementById('modalImg');
    
    modal.removeEventListener('touchstart', handleTouchStart);
    modal.removeEventListener('touchmove', handleTouchMove);
    modal.removeEventListener('touchend', handleTouchEnd);
    
    // Reset image position
    modalImg.classList.remove('sliding');
    modalImg.style.transform = '';
}

// Handle touch start
function handleTouchStart(event) {
    touchStartX = event.changedTouches[0].screenX;
    isSwiping = true;
}

// Handle touch move
function handleTouchMove(event) {
    if (!isSwiping) return;
    
    const modalImg = document.getElementById('modalImg');
    touchMoveX = event.changedTouches[0].screenX;
    const deltaX = touchMoveX - touchStartX;
    
    // Add sliding class
    modalImg.classList.add('sliding');
    
    // Update image position in real-time
    modalImg.style.transform = `translateX(${deltaX}px)`;
    
    event.preventDefault(); // Prevent page scrolling
}

// Handle touch end
function handleTouchEnd(event) {
    if (!isSwiping) return;
    
    const modalImg = document.getElementById('modalImg');
    touchEndX = event.changedTouches[0].screenX;
    const deltaX = touchEndX - touchStartX;
    
    // Remove sliding class
    modalImg.classList.remove('sliding');
    
    // Reset image position
    modalImg.style.transform = '';
    
    // Check if it's a valid swipe
    const swipeThreshold = 50;
    if (Math.abs(deltaX) > swipeThreshold) {
        if (deltaX < 0) {
            // Swipe left, show next image
            changeImage(1, { stopPropagation: function() {} });
        } else {
            // Swipe right, show previous image
            changeImage(-1, { stopPropagation: function() {} });
        }
    }
    
    isSwiping = false;
}

// Handle swipe gesture
function handleSwipeGesture() {
    // This function is now handled by handleTouchEnd
}

function changeImage(dir, e) {
    e.stopPropagation();
    let idx = currentImageIndex + dir;
    if (idx < 0) idx = images.length - 1;
    if (idx >= images.length) idx = 0;
    currentImageIndex = idx; // 更新当前图片索引
    openModal(idx);
}

// Handle modal click event
function handleModalClick(event) {
    // Close modal when clicking on the background (not the image or buttons)
    if (event.target.id === 'imgModal') {
        closeModal();
    }
}

document.addEventListener('keydown', e => {
    const modal = document.getElementById('imgModal');
    if (modal.style.display !== 'flex') return;
    if (e.key === 'Escape') closeModal();
    else if (e.key === 'ArrowLeft') changeImage(-1, e);
    else if (e.key === 'ArrowRight') changeImage(1, e);
});

/* ========= FAQ Accordion ========= */
document.addEventListener('DOMContentLoaded', () => {
    const faq = document.querySelector('.faq-container');
    if (!faq) return;
    faq.querySelectorAll('.faq-answer').forEach(a => a.style.maxHeight = '0px');
    faq.addEventListener('click', e => {
        const q = e.target.closest('.faq-question');
        if (!q) return;
        const a = q.nextElementSibling, content = a.querySelector('.faq-answer-content');
        const open = a.style.maxHeight !== '0px';
        faq.querySelectorAll('.faq-answer').forEach(x => x.style.maxHeight = '0px');
        if (!open) {
            requestAnimationFrame(() => {
                a.style.maxHeight = '10000px';
                requestAnimationFrame(() => { a.style.maxHeight = (content.scrollHeight + 10) + 'px'; });
            });
        }
    });
});

/* ========= Year ========= */
document.getElementById('current-year').textContent = new Date().getFullYear();
</script>
</body>
</html>