<?php
if (! function_exists('trust_e')) {
    function trust_e($value): string { return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8'); }
}
if (! function_exists('trust_reviews_int')) {
    function trust_reviews_int($count): int { return (int) preg_replace('/[^\d]/', '', (string) $count); }
}
if (! function_exists('trust_rating_float')) {
    function trust_rating_float($rating): float { return (float) $rating; }
}
if (! function_exists('trust_stars')) {
    function trust_stars($rating): string {
        $filled = (int) round(min(5, max(0, (float) $rating)));
        return str_repeat('★', $filled) . str_repeat('☆', 5 - $filled);
    }
}

$brand = $data['Brand'] ?? 'Retailer';
$subcategory = $data['subcategory'] ?? 'Products';
$updated = $data['updated'] ?? '';
$reviewSources = is_array($data['review_sources'] ?? null) ? $data['review_sources'] : [];
$products = is_array($data['products'] ?? null) ? $data['products'] : [];
$pageTitle = 'STORE.com – ' . $subcategory . ' Reviews & Trust';
$year = date('Y');

$totalReviews = 0;
$ratingSum = 0.0;
$ratedCount = 0;
$bestRating = 0.0;
$bestRatedName = '';
$mostReviewed = 0;

foreach ($products as $product) {
    $reviews = trust_reviews_int($product['review_count'] ?? 0);
    $totalReviews += $reviews;
    $mostReviewed = max($mostReviewed, $reviews);
    if (($product['rating'] ?? '') !== '') {
        $rating = trust_rating_float($product['rating']);
        $ratingSum += $rating;
        $ratedCount++;
        if ($rating >= $bestRating) {
            $bestRating = $rating;
            $bestRatedName = $product['brand'] ?? ($product['name'] ?? '');
        }
    }
}

$avgRating = $ratedCount > 0 ? number_format($ratingSum / $ratedCount, 1) : '—';
$trustBadges = [];
foreach ($products as $product) {
    if (!empty($product['certification'])) {
        $trustBadges[] = $product['certification'];
    }
}
if ($mostReviewed > 0) {
    $trustBadges[] = number_format($mostReviewed) . '+ reviews on a top pick';
}
$trustBadges[] = $brand . ' shopper ratings';
$trustBadges = array_slice(array_values(array_unique($trustBadges)), 0, 4);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= trust_e($pageTitle) ?></title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="style.css">
</head>
<body class="bg-light-gradient">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <header class="header">
        <div class="container-fluid header-row">
            <a href="#" class="logo"><?= trust_e($brand) ?></a>
            <span class="header-pill"><?= trust_e($subcategory) ?></span>
        </div>
    </header>

    <div class="main-container custom-container">
        <section class="card border border-color radius-18 card-shadow bg-color-white p-4">
            <?php if ($updated !== ''): ?>
                <p class="sp-eyebrow text-xs">Updated <?= trust_e($updated) ?> · <?= trust_e($brand) ?></p>
            <?php endif; ?>
            <h1 class="sp-h1 heading-lg color-content fw-800">Rated, reviewed, and shopper-backed</h1>
            <p class="text-md color-muted">These <?= trust_e(strtolower($subcategory)) ?> earned their place from review volume and star averages at <?= trust_e($brand) ?> — not from a single marketing claim.</p>
            <div class="proof-stats">
                <div class="proof-stat">
                    <strong><?= $totalReviews > 0 ? trust_e(number_format($totalReviews) . '+') : '—' ?></strong>
                    <span>Combined <?= trust_e($brand) ?> reviews</span>
                </div>
                <div class="proof-stat">
                    <strong><?= $avgRating !== '—' ? trust_e($avgRating . '/5') : '—' ?></strong>
                    <span>Typical rating across the set</span>
                </div>
                <div class="proof-stat">
                    <strong><?= $bestRating > 0 ? trust_e(number_format($bestRating, 1) . '/5') : '—' ?></strong>
                    <span>Highest average<?= $bestRatedName !== '' ? ' (' . trust_e($bestRatedName) . ')' : '' ?></span>
                </div>
            </div>
            <?php if ($trustBadges): ?>
                <div class="chip-row mt-3 mb-0">
                    <?php foreach ($trustBadges as $badge): ?>
                        <span class="chip"><?= trust_e($badge) ?></span>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </section>

        <section id="products" class="mb-3 mt-4">
            <?php foreach ($products as $index => $product):
                $name = $product['name'] ?? 'Untitled product';
                $image = $product['image_url'] ?? '';
                $url = $product['retailer_url'] ?? '#';
                $bestFor = $product['best_for'] ?? '';
                $rating = $product['rating'] ?? '';
                $reviews = $product['review_count'] ?? '';
                $chips = is_array($product['chips'] ?? null) ? $product['chips'] : [];
                $quote = $product['why_it_stands_out'] ?? ($product['summary_short'] ?? '');
                $quoteFooter = trim($brand . ' shoppers' . ($bestFor !== '' ? ' · ' . $bestFor : ''));
            ?>
            <div class="bg-color-white border border-color radius-18 p-0 mb-3 shadow1-sm">
                <div class="product-img">
                    <?php if ($image !== ''): ?>
                        <img src="<?= trust_e($image) ?>" alt="<?= trust_e($name) ?>" loading="lazy">
                    <?php endif; ?>
                </div>
                <div class="product-body">
                    <?php if ($bestFor !== ''): ?>
                        <p class="product-kicker text-color-green text-xs"><?= trust_e($bestFor) ?></p>
                    <?php endif; ?>
                    <h2 class="product-name"><?= trust_e($name) ?></h2>
                    <div class="quick-meta">
                        <?php if ($rating !== ''): ?>
                            <span class="rating-tag"><span class="stars"><?= trust_e(trust_stars($rating)) ?></span>&nbsp;<?= trust_e($rating) ?>/5</span>
                        <?php endif; ?>
                        <?php if ($reviews !== ''): ?>
                            <span class="price-tag"><?= trust_e($reviews) ?> reviews</span>
                        <?php endif; ?>
                    </div>
                    <?php if ($quote !== ''): ?>
                        <blockquote class="quote-box mt-3">
                            <?= trust_e($quote) ?>
                            <footer><?= trust_e($quoteFooter) ?></footer>
                        </blockquote>
                    <?php endif; ?>
                    <?php if ($chips): ?>
                        <div class="chip-row">
                            <?php foreach ($chips as $chip): ?>
                                <span class="chip"><?= trust_e($chip) ?></span>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                    <div class="row g-2 mb-0">
                        <div class="col-md-6">
                            <a href="<?= trust_e($url) ?>" class="btn-amazon" target="_blank" rel="noopener noreferrer">Read reviews &amp; shop on <?= trust_e($brand) ?></a>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </section>

        <?php if ($reviewSources): ?>
        <section class="mt-4">
            <div class="card border-0 border-color radius-18 bg-color-white p-md-4 p-3">
                <h6 class="mb-3 text-sm color-content fw-700">Sources we reviewed</h6>
                <ul class="ps-0 d-flex flex-column gap-2 mb-0">
                    <?php foreach ($reviewSources as $source): ?>
                        <li class="color-muted text-xs"><?= trust_e(is_array($source) ? implode(' — ', $source) : $source) ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </section>
        <?php endif; ?>

        <div class="card border border-color radius-18 card-shadow bg-color-white p-md-4 p-3 mt-4">
            <p class="mb-2 text-md color-content fw-700">How this page is built</p>
            <p class="text-sm color-muted">store.com aggregates and summarizes published insights from multiple product review sources to help shoppers compare products faster. Pricing, ratings, and retailer details may change, so always confirm the latest information on the retailer page before buying.</p>
        </div>
    </div>

    <footer class="footer text-center">
        © <?= (int) $year ?> STORE.com · <a href="#" class="text-decoration-underline">Privacy policy</a> · <a href="#" class="text-decoration-underline"> Terms of Use </a>
    </footer>
    <script src="script.js"></script>
</body>
</html>
