<?php

declare(strict_types=1);
/** @var list<array<string,mixed>> $stores */
/** @var string|null $dbError */
/** @var string|null $storesError */
/** @var list<string> $cities */
/** @var Closure $buildQuery */
/** @var array{id:int,username:string,display_name:string,avatar_rel:string}|null $fatePublicMember */
/** @var bool $fateAdminNavVisible */
/** @var bool $fateForumNavVisible */
/** @var bool $fateBlogNavVisible */
/** @var string $fateBlogNavLabel */
/** @var list<array<string,mixed>> $blogHomeAnnouncements */
/** @var string $cityFilter */
/** @var string $sort */
/** @var string $storeSearchQ */
/** @var string $storeSearchMode */
/** @var list<array<string,mixed>> $weeklyTopStores */
/** @var string $weeklyStatsRangeLabel */
/** @var Closure $buildHomeQuery */
/** @var int $storeSearchTotal */
/** @var PDO|null $pdo */
/** @var string $listingFilter */

$fateMinimalIncludePageStyles = true;
require __DIR__ . DIRECTORY_SEPARATOR . 'partials' . DIRECTORY_SEPARATOR . 'head.php';
require_once dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_store_listing.php';
require_once dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_template.php';

$fateSearchActive = ($storeSearchQ ?? '') !== '';
$fateSearchFuzzy = $fateSearchActive && (($storeSearchMode ?? '') === FATE_STORE_SEARCH_MODE_FUZZY);
$isMobileListingTab = ($listingFilter ?? FATE_STORE_LISTING_FIXED) === FATE_STORE_LISTING_MOBILE;
$weeklyHeroLabel = $isMobileListingTab ? '本週熱門非定點 TOP10' : '本週熱門定點 TOP10';
$weeklyHeroAria = $isMobileListingTab ? '本週熱門非定點服務' : '本週熱門定點店家';
?>
<body>
<?php require __DIR__ . DIRECTORY_SEPARATOR . 'partials' . DIRECTORY_SEPARATOR . 'bar.php'; ?>

<div class="minimal-page minimal-page--home">
    <div class="layout-shell">
        <div class="layout layout--home">
            <div class="layout-main minimal-home">
    <header class="minimal-hero">
        <h1 class="minimal-hero__title"><?= htmlspecialchars($fateBrand['title_main'], ENT_QUOTES, 'UTF-8') ?></h1>
        <p class="minimal-hero__lead"><?= htmlspecialchars($fateBrand['title_sub'], ENT_QUOTES, 'UTF-8') ?> · 瀏覽與探索店家資訊</p>
    </header>

    <?php if (!$fateSearchActive && ($weeklyTopStores ?? []) !== []): ?>
        <section class="minimal-weekly minimal-weekly--listing-<?= $isMobileListingTab ? 'mobile' : 'fixed' ?>" id="minimalWeeklyHero" aria-roledescription="carousel" aria-label="<?= htmlspecialchars($weeklyHeroAria, ENT_QUOTES, 'UTF-8') ?>">
            <span class="minimal-weekly__label"><?= htmlspecialchars($weeklyHeroLabel, ENT_QUOTES, 'UTF-8') ?></span>
            <?php if (($weeklyStatsRangeLabel ?? '') !== ''): ?>
                <p class="minimal-weekly__sub"><?= htmlspecialchars($weeklyStatsRangeLabel, ENT_QUOTES, 'UTF-8') ?> · 依詳情頁瀏覽</p>
            <?php endif; ?>
            <div class="minimal-weekly__track">
                <?php foreach ($weeklyTopStores as $wi => $wr): ?>
                    <?php
                    $wsid = (int) ($wr['spa_store_id'] ?? 0);
                    $wname = trim((string) ($wr['store_name'] ?? ''));
                    if ($wname === '') {
                        $wname = '店家 #' . $wsid;
                    }
                    $wcity = trim((string) ($wr['city_name'] ?? ''));
                    $wdist = trim((string) ($wr['district_name'] ?? ''));
                    $wloc = $isMobileListingTab
                        ? fate_store_listing_location_text($wr)
                        : trim($wcity . ($wcity !== '' && $wdist !== '' ? ' · ' : '') . $wdist);
                    $whits = isset($wr['week_hits']) ? (int) $wr['week_hits'] : 0;
                    $wrating = isset($wr['place_rating']) && $wr['place_rating'] !== '' && $wr['place_rating'] !== null
                        ? (float) $wr['place_rating']
                        : null;
                    $wCover = fate_store_cover_src(
                        isset($wr['cover_photo_path']) ? (string) $wr['cover_photo_path'] : null,
                        isset($wr['photos_json']) ? (string) $wr['photos_json'] : null
                    );
                    $wImg = fate_spa_asset_url($wCover['path']);
                    $wUrl = 'store.php?id=' . $wsid;
                    ?>
                    <article class="minimal-weekly__slide<?= $wi === 0 ? ' is-active' : '' ?>"
                             data-minimal-hero-slide="<?= (int) $wi ?>"
                             aria-hidden="<?= $wi === 0 ? 'false' : 'true' ?>">
                        <a class="minimal-weekly__link" href="<?= htmlspecialchars($wUrl, ENT_QUOTES, 'UTF-8') ?>">
                            <?php if ($wImg !== null): ?>
                                <img class="minimal-weekly__cover" src="<?= htmlspecialchars($wImg, ENT_QUOTES, 'UTF-8') ?>"
                                     onerror="this.onerror=null; this.src='<?= htmlspecialchars(fate_local_asset_url($wCover['path']) ?? '') ?>';"
                                     alt="" loading="<?= $wi === 0 ? 'eager' : 'lazy' ?>">
                            <?php else: ?>
                                <div class="minimal-weekly__cover minimal-weekly__cover--empty">NO IMAGE</div>
                            <?php endif; ?>
                            <div class="minimal-weekly__overlay" aria-hidden="true"></div>
                            <div class="minimal-weekly__content">
                                <span class="minimal-weekly__rank">#<?= (int) $wi + 1 ?></span>
                                <h2 class="minimal-weekly__title"><?= htmlspecialchars($wname, ENT_QUOTES, 'UTF-8') ?></h2>
                                <div class="minimal-weekly__meta">
                                    <?php if ($wloc !== ''): ?><span><?= htmlspecialchars($wloc, ENT_QUOTES, 'UTF-8') ?></span><?php endif; ?>
                                    <span>本週 <?= number_format($whits) ?> 次瀏覽</span>
                                    <?php if ($wrating !== null): ?><span>★ <?= htmlspecialchars(number_format($wrating, 1), ENT_QUOTES, 'UTF-8') ?></span><?php endif; ?>
                                </div>
                            </div>
                        </a>
                    </article>
                <?php endforeach; ?>
            </div>
            <?php if (count($weeklyTopStores) > 1): ?>
                <button type="button" class="minimal-weekly__nav minimal-weekly__nav--prev" data-minimal-hero-nav="prev" aria-label="上一張">‹</button>
                <button type="button" class="minimal-weekly__nav minimal-weekly__nav--next" data-minimal-hero-nav="next" aria-label="下一張">›</button>
                <div class="minimal-weekly__dots" role="tablist" aria-label="輪播頁碼">
                    <?php foreach ($weeklyTopStores as $wi => $_wr): ?>
                        <button type="button" role="tab" class="minimal-weekly__dot<?= $wi === 0 ? ' is-active' : '' ?>"
                                data-minimal-hero-dot="<?= (int) $wi ?>"
                                aria-selected="<?= $wi === 0 ? 'true' : 'false' ?>"
                                aria-label="第 <?= (int) $wi + 1 ?> 張"></button>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </section>
        <script>
        (function () {
            var hero = document.getElementById('minimalWeeklyHero');
            if (!hero) return;
            var slides = hero.querySelectorAll('[data-minimal-hero-slide]');
            var dots = hero.querySelectorAll('[data-minimal-hero-dot]');
            var n = slides.length;
            if (n < 2) return;
            var current = 0;
            var timer = null;
            var intervalMs = 5200;
            var reduceMotion = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
            function show(index) {
                current = (index % n + n) % n;
                slides.forEach(function (slide, i) {
                    var on = i === current;
                    slide.classList.toggle('is-active', on);
                    slide.setAttribute('aria-hidden', on ? 'false' : 'true');
                });
                dots.forEach(function (dot, i) {
                    var on = i === current;
                    dot.classList.toggle('is-active', on);
                    dot.setAttribute('aria-selected', on ? 'true' : 'false');
                });
            }
            function next() { show(current + 1); }
            function start() {
                if (reduceMotion || timer) return;
                timer = setInterval(next, intervalMs);
            }
            function stop() { if (timer) { clearInterval(timer); timer = null; } }
            hero.querySelectorAll('[data-minimal-hero-nav]').forEach(function (btn) {
                btn.addEventListener('click', function () {
                    stop();
                    show(current + (btn.getAttribute('data-minimal-hero-nav') === 'next' ? 1 : -1));
                    start();
                });
            });
            dots.forEach(function (dot) {
                dot.addEventListener('click', function () {
                    stop();
                    show(parseInt(dot.getAttribute('data-minimal-hero-dot'), 10));
                    start();
                });
            });
            hero.addEventListener('mouseenter', stop);
            hero.addEventListener('mouseleave', start);
            start();
        })();
        </script>
    <?php endif; ?>

    <?php require dirname(__DIR__) . DIRECTORY_SEPARATOR . 'default' . DIRECTORY_SEPARATOR . 'partials' . DIRECTORY_SEPARATOR . 'home_listing_tabs.inc.php'; ?>

    <section class="minimal-panel minimal-panel--filter" aria-label="篩選">
        <div class="minimal-toolbar">
            <div class="minimal-toolbar__group">
                <label class="minimal-toolbar__label" for="city">縣市</label>
                <select class="minimal-select" id="city" name="city" form="f-filter">
                    <option value="">全部</option>
                    <?php foreach ($cities as $c): ?>
                        <option value="<?= htmlspecialchars($c, ENT_QUOTES, 'UTF-8') ?>" <?= $cityFilter === $c ? 'selected' : '' ?>><?= htmlspecialchars($c, ENT_QUOTES, 'UTF-8') ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="minimal-toolbar__group">
                <label class="minimal-toolbar__label" for="sort">排序</label>
                <select class="minimal-select" id="sort" name="sort" form="f-filter">
                    <option value="rating" <?= $sort === 'rating' ? 'selected' : '' ?>>評分優先</option>
                    <option value="name" <?= $sort === 'name' ? 'selected' : '' ?>>名稱</option>
                    <option value="recent" <?= $sort === 'recent' ? 'selected' : '' ?>>最近同步</option>
                </select>
            </div>
            <form id="f-filter" method="get" action="./">
                <input type="hidden" name="page" value="1">
                <?php if ($isMobileListingTab): ?>
                    <input type="hidden" name="listing" value="mobile">
                <?php endif; ?>
                <?php if (($storeSearchQ ?? '') !== ''): ?>
                    <input type="hidden" name="q" value="<?= htmlspecialchars($storeSearchQ, ENT_QUOTES, 'UTF-8') ?>">
                <?php endif; ?>
                <button type="submit" class="minimal-btn">套用</button>
                <?php if ($cityFilter !== '' || $sort !== 'rating' || ($storeSearchQ ?? '') !== ''): ?>
                    <a class="minimal-btn" href="<?= htmlspecialchars($buildQuery(['city' => null, 'sort' => null, 'q' => null, 'page' => null, 'listing' => $isMobileListingTab ? 'mobile' : null]), ENT_QUOTES, 'UTF-8') ?>">重設</a>
                <?php endif; ?>
            </form>
            <div class="minimal-stats">
                <?php if ($dbError === null && $storesError === null): ?>
                    共 <strong><?= (int) $storeTotal ?></strong> 筆<?= $isMobileListingTab ? '非定點服務' : '定點店家' ?>
                    <?php if ($lastSyncMax !== null): ?>
                        · 同步 <?= htmlspecialchars($lastSyncMax, ENT_QUOTES, 'UTF-8') ?>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </section>

    <?php if ($fateSearchActive): ?>
        <div class="minimal-search-summary<?= $fateSearchFuzzy ? ' minimal-search-summary--fuzzy' : '' ?>" role="status" aria-live="polite">
            <?php if ($fateSearchFuzzy): ?>
                <span class="minimal-search-summary__badge">模糊搜尋</span>
            <?php endif; ?>
            <span class="minimal-search-summary__title"><?= $fateSearchFuzzy ? '模糊搜尋結果' : '搜尋結果' ?></span>
            <?php if ($fateSearchFuzzy): ?>
                <span class="minimal-search-summary__hint">精準無結果，以下為模糊比對</span>
            <?php endif; ?>
            關鍵字「<strong><?= htmlspecialchars($storeSearchQ, ENT_QUOTES, 'UTF-8') ?></strong>」
            · 找到 <strong><?= (int) $storeTotal ?></strong> 筆<?= $fateSearchFuzzy ? '相近' : '' ?>店家
            · <a href="./">清除搜尋</a>
        </div>
    <?php endif; ?>

    <?php if ($dbError !== null): ?>
        <div class="minimal-empty">無法連線資料庫：<code class="inline"><?= htmlspecialchars($dbError, ENT_QUOTES, 'UTF-8') ?></code></div>
    <?php elseif ($storesError !== null): ?>
        <div class="minimal-empty">無法讀取資料表：<code class="inline"><?= htmlspecialchars($storesError, ENT_QUOTES, 'UTF-8') ?></code></div>
    <?php elseif ($stores === []): ?>
        <div class="minimal-empty">
            尚無符合條件的<?= $isMobileListingTab ? '非定點服務' : '定點店家' ?><?= ($storeSearchQ ?? '') !== '' ? '（含模糊搜尋）' : '' ?><?= ($storeSearchQ ?? '') !== '' ? '，請調整關鍵字或縣市' : '' ?>
            · <?php if (!$isMobileListingTab && !empty($fateAdminNavVisible)): ?><a href="admin/">後台同步</a><?php elseif (!$isMobileListingTab): ?>請待管理員同步<?php else: ?>可至會員中心提交非定點服務<?php endif; ?>
        </div>
    <?php else: ?>
        <?php if ($fateSearchFuzzy): ?>
            <p class="minimal-search-fuzzy-label" role="note">以下為<strong>模糊搜尋</strong>結果，非精準匹配。</p>
        <?php endif; ?>
        <div class="minimal-list">
            <?php foreach ($stores as $row): ?>
                <?php
                $sid = (int) ($row['spa_store_id'] ?? 0);
                $name = trim((string) ($row['store_name'] ?? ''));
                if ($name === '') {
                    $name = '店家 #' . $sid;
                }
                $isMobileListing = fate_store_listing_is_mobile($row);
                $listingLabel = fate_store_listing_label(fate_store_listing_kind_from_row($row));
                $addr = fate_store_listing_location_text($row);
                $city = trim((string) ($row['city_name'] ?? ''));
                $dist = trim((string) ($row['district_name'] ?? ''));
                $rating = isset($row['place_rating']) && $row['place_rating'] !== '' && $row['place_rating'] !== null
                    ? (float) $row['place_rating']
                    : null;
                $rCount = isset($row['place_ratings_total']) ? (int) $row['place_ratings_total'] : null;
                $storeLocalUrl = 'store.php?id=' . $sid;
                $coverInfo = fate_store_cover_src(
                    isset($row['cover_photo_path']) ? (string) $row['cover_photo_path'] : null,
                    isset($row['photos_json']) ? (string) $row['photos_json'] : null
                );
                $imgUrl = fate_spa_asset_url($coverInfo['path']);
                $loc = trim($city . ($city !== '' && $dist !== '' ? ' ' : '') . $dist);
                ?>
                <article class="minimal-card minimal-card--listing-<?= $isMobileListing ? 'mobile' : 'fixed' ?>">
                    <a class="minimal-card__media" href="<?= htmlspecialchars($storeLocalUrl, ENT_QUOTES, 'UTF-8') ?>" aria-label="查看 <?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?>">
                        <?php if ($imgUrl !== null): ?>
                            <img class="minimal-card__thumb" src="<?= htmlspecialchars($imgUrl, ENT_QUOTES, 'UTF-8') ?>"
                                 onerror="this.onerror=null; this.src='<?= htmlspecialchars(fate_local_asset_url($coverInfo['path']) ?? '') ?>';"
                                 alt="" loading="lazy">
                        <?php else: ?>
                            <div class="minimal-card__thumb-ph">—</div>
                        <?php endif; ?>
                        <?php if ($rating !== null): ?>
                            <span class="minimal-card__rating" title="Google 評分">
                                <span class="minimal-card__rating-star" aria-hidden="true">★</span>
                                <?= htmlspecialchars(number_format($rating, 1), ENT_QUOTES, 'UTF-8') ?>
                            </span>
                        <?php endif; ?>
                    </a>
                    <div class="minimal-card__body">
                        <h2 class="minimal-card__title"><a href="<?= htmlspecialchars($storeLocalUrl, ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?></a></h2>
                        <?php if ($rating !== null): ?>
                            <p class="card-rating-row" aria-label="Google 評分 <?= htmlspecialchars(number_format($rating, 1), ENT_QUOTES, 'UTF-8') ?>">
                                <span class="card-rating-row__star" aria-hidden="true">★</span>
                                <span class="card-rating-row__score"><?= htmlspecialchars(number_format($rating, 1), ENT_QUOTES, 'UTF-8') ?></span>
                                <span class="card-rating-row__brand">Google</span>
                                <?php if ($rCount !== null && $rCount > 0): ?>
                                    <span class="card-rating-row__cnt">(<?= (int) $rCount ?> 則評價)</span>
                                <?php endif; ?>
                            </p>
                        <?php endif; ?>
                        <?php if ($isMobileListing): ?>
                            <div class="minimal-card__meta minimal-card__meta--listing"><span class="minimal-badge"><?= htmlspecialchars($listingLabel, ENT_QUOTES, 'UTF-8') ?></span></div>
                        <?php elseif ($loc !== ''): ?>
                            <div class="minimal-card__meta minimal-card__meta--region"><?= htmlspecialchars($loc, ENT_QUOTES, 'UTF-8') ?></div>
                        <?php endif; ?>
                        <?php if ($addr !== ''): ?>
                            <div class="minimal-card__meta<?= $isMobileListing ? ' minimal-card__meta--service-area' : ' minimal-card__meta--address' ?>"><?= htmlspecialchars($addr, ENT_QUOTES, 'UTF-8') ?></div>
                        <?php endif; ?>
                        <div class="minimal-card__foot">
                            <span class="minimal-card__id">#<?= $sid ?></span>
                            <a class="minimal-card__link" href="<?= htmlspecialchars($storeLocalUrl, ENT_QUOTES, 'UTF-8') ?>">查看詳情</a>
                        </div>
                    </div>
                </article>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <?php if (($dbError === null && $storesError === null) && $storeTotal > $perPage): ?>
        <nav class="minimal-pager" aria-label="分頁">
            <?php if ($page > 1): ?>
                <a href="./<?= htmlspecialchars($buildQuery(['page' => (string) ($page - 1)]), ENT_QUOTES, 'UTF-8') ?>">上一頁</a>
            <?php else: ?>
                <span class="disabled">上一頁</span>
            <?php endif; ?>
            <span class="cur"><?= (int) $page ?> / <?= (int) $totalPages ?></span>
            <?php if ($page < $totalPages): ?>
                <a href="./<?= htmlspecialchars($buildQuery(['page' => (string) ($page + 1)]), ENT_QUOTES, 'UTF-8') ?>">下一頁</a>
            <?php else: ?>
                <span class="disabled">下一頁</span>
            <?php endif; ?>
        </nav>
    <?php endif; ?>
            </div>

            <?php require fate_template_theme_partial('sidebar.php'); ?>
        </div>
    </div>
</div>

<?php require __DIR__ . DIRECTORY_SEPARATOR . 'partials' . DIRECTORY_SEPARATOR . 'footer.php'; ?>
