<?php
if (! function_exists('cmp_e')) {
    function cmp_e($value): string {
        return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
    }
}
if (! function_exists('cmp_reviews_int')) {
    function cmp_reviews_int($count): int {
        return (int) preg_replace('/[^\d]/', '', (string) $count);
    }
}
if (! function_exists('cmp_rating_float')) {
    function cmp_rating_float($rating): float {
        return (float) $rating;
    }
}
if (! function_exists('cmp_price_float')) {
    function cmp_price_float($price): float {
        return (float) preg_replace('/[^\d.]/', '', (string) $price);
    }
}

$brand = $data['Brand'] ?? 'Retailer';
$subcategory = $data['subcategory'] ?? 'Products';
$updated = $data['updated'] ?? '';
$heroTitle = $data['hero_title'] ?? ('The Best ' . $subcategory);
$reviewSources = is_array($data['review_sources'] ?? null) ? $data['review_sources'] : [];
$products = is_array($data['products'] ?? null) ? $data['products'] : [];
$pageTitle = 'STORE.com – ' . $subcategory . ' Comparison';
$year = date('Y');
$winnerIndex = 0;
foreach ($products as $i => $product) {
    if (strcasecmp((string) ($product['best_for'] ?? ''), 'Best Overall') === 0) {
        $winnerIndex = $i;
        break;
    }
}

$bestRating = 0.0;
$bestReviews = 0;
$bestPrice = null;
foreach ($products as $product) {
    $bestRating = max($bestRating, cmp_rating_float($product['rating'] ?? 0));
    $bestReviews = max($bestReviews, cmp_reviews_int($product['review_count'] ?? 0));
    if (!empty($product['price'])) {
        $priceVal = cmp_price_float($product['price']);
        $bestPrice = $bestPrice === null ? $priceVal : min($bestPrice, $priceVal);
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= cmp_e($brand) ?></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"><?= cmp_e($brand) ?></a>
            <span class="header-pill"><?= cmp_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 <?= cmp_e($updated) ?> · <?= cmp_e($brand) ?></p>
            <?php endif; ?>
            <h1 class="sp-h1 heading-lg color-content fw-800"><?= cmp_e($heroTitle) ?></h1>
            <p class="text-md color-muted">Price, rating, and standout features — lined up so you can pick the right <?= cmp_e(strtolower($subcategory)) ?> without guessing.</p>
            <div class="row">
                <div class="col-xl-6 col-md-6 col-sm-12">
                    <a href="#products" class="button-style bg-color-white border border-color color-content text-sm fw-800">Shop Top Picks</a>
                </div>
                <div class="col-xl-6 col-md-6 col-sm-12">
                    <a href="#comparison" class="button-style bg-color-white border border-color color-content text-sm fw-800 mt-md-0 mt-2">Compare</a>
                </div>
            </div>
        </section>

        <section class="mt-4" id="comparison">
            <p class="sp-section-eyebrow mb-2 product-kicker">Quick comparison</p>
            <h2 class="sp-section-title text-md fw-700 color-content">Compare all options</h2>

            <div class="compare-table-wrap mb-4">
                <table class="compare-table">
                    <thead>
                        <tr>
                            <th>Product</th>
                            <th>Price</th>
                            <th>Best for</th>
                            <th>Rating</th>
                            <th>Reviews</th>
                            <th>Standout</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($products as $index => $product):
                            $isWinner = $index === $winnerIndex;
                            $name = $product['name'] ?? 'Untitled product';
                            $image = $product['image_url'] ?? '';
                            $url = $product['retailer_url'] ?? '#';
                            $price = $product['price'] ?? '';
                            $bestFor = $product['best_for'] ?? '';
                            $rating = $product['rating'] ?? '';
                            $reviews = $product['review_count'] ?? '';
                            $standout = $product['why_short'] ?? ($product['chips'][0] ?? '');
                            $isBestPrice = $price !== '' && $bestPrice !== null && cmp_price_float($price) === $bestPrice;
                            $isBestRating = $rating !== '' && cmp_rating_float($rating) === $bestRating && $bestRating > 0;
                            $isBestReviews = $reviews !== '' && cmp_reviews_int($reviews) === $bestReviews && $bestReviews > 0;
                        ?>
                        <tr<?= $isWinner ? ' class="is-winner"' : '' ?>>
                            <td>
                                <div class="cell-product">
                                    <?php if ($image !== ''): ?>
                                        <img class="cell-thumb" src="<?= cmp_e($image) ?>" alt="">
                                    <?php endif; ?>
                                    <p class="cell-name"><span class="cell-rank"><?= (int) ($index + 1) ?></span> <?= cmp_e($name) ?></p>
                                </div>
                            </td>
                            <td class="<?= $isBestPrice ? 'cell-score best' : '' ?>"><?= $price !== '' ? cmp_e($price) : '—' ?></td>
                            <td><?= $bestFor !== '' ? cmp_e($bestFor) : '—' ?></td>
                            <td class="<?= $isBestRating ? 'cell-score best' : '' ?>"><?= $rating !== '' ? cmp_e($rating) . '/5' : '—' ?></td>
                            <td class="<?= $isBestReviews ? 'cell-score best' : '' ?>"><?= $reviews !== '' ? cmp_e($reviews) : '—' ?></td>
                            <td><?= $standout !== '' ? cmp_e($standout) : '—' ?></td>
                            <td><a class="table-cta" href="<?= cmp_e($url) ?>" target="_blank" rel="noopener noreferrer">Shop</a></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <div class="compare-card-main row g-3">
                <?php foreach ($products as $product):
                    $name = $product['name'] ?? 'Untitled product';
                    $bestFor = $product['best_for'] ?? '—';
                    $chip = $product['chips'][0] ?? '—';
                    $rating = $product['rating'] ?? '—';
                    $price = $product['price'] ?? '—';
                ?>
                <div class="col-md-4 col-sm-6">
                    <article class="compare-card">
                        <h3 class="text-md color-content fw-700 mb-3"><?= cmp_e($name) ?></h3>
                        <ul class="list ps-3 d-flex flex-column mb-0">
                            <li class="text-md color-muted mb-0"><strong>Often recommended for: </strong><?= cmp_e($bestFor) ?></li>
                            <li class="text-md color-muted mb-0"><strong>Standout: </strong><?= cmp_e($chip) ?></li>
                            <li class="text-md color-muted mb-0"><strong>Rating: </strong><?= cmp_e($rating) ?>/5</li>
                            <li class="text-md color-muted mb-0"><strong>Price: </strong><?= cmp_e($price) ?></li>
                        </ul>
                    </article>
                </div>
                <?php endforeach; ?>
            </div>
        </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'] ?? '';
                $price = $product['price'] ?? '';
                $listPrice = $product['list_price'] ?? null;
                $discount = $product['discount'] ?? null;
                $rating = $product['rating'] ?? '';
                $reviews = $product['review_count'] ?? '';
                $summary = $product['summary'] ?? ($product['summary_short'] ?? '');
                $chips = is_array($product['chips'] ?? null) ? $product['chips'] : [];
                $why = $product['why_it_stands_out'] ?? '';
                $tradeoff = $product['tradeoff_note'] ?? '';
            ?>
            <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="<?= cmp_e($image) ?>" alt="<?= cmp_e($name) ?>" loading="lazy">
                    <?php endif; ?>
                </div>
                <div class="product-body">
                    <div class="product-top">
                        <div>
                            <?php if ($bestFor !== ''): ?>
                                <p class="product-kicker text-color-green text-xs"><?= cmp_e($bestFor) ?></p>
                            <?php endif; ?>
                            <h2 class="product-name"><?= cmp_e($name) ?></h2>
                        </div>
                        <div class="price-block">
                            <?php if ($price !== ''): ?>
                                <div class="price"><?= cmp_e($price) ?><?php if (!empty($listPrice)): ?> <span class="old-price"><?= cmp_e($listPrice) ?></span><?php endif; ?></div>
                            <?php endif; ?>
                            <?php if ($rating !== '' || $reviews !== ''): ?>
                                <div class="rating"><?= cmp_e(trim($rating . ($rating !== '' ? '/5' : '') . ($reviews !== '' ? ' · ' . $reviews . ' reviews' : ''))) ?></div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php if ($summary !== ''): ?>
                        <p class="product-summary"><?= cmp_e($summary) ?></p>
                    <?php endif; ?>
                    <?php if ($chips): ?>
                        <div class="chip-row">
                            <?php foreach ($chips as $chip): ?>
                                <span class="chip"><?= cmp_e($chip) ?></span>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                    <div class="row g-2 mb-3">
                        <?php if ($why !== ''): ?>
                            <div class="col-md-6">
                                <div class="bg-color-gray-50 border border-color p-3 rounded-3 h-100">
                                    <p class="text-lg fw-700 color-content mb-1">Why it shows up often</p>
                                    <p class="text-sm color-muted"><?= cmp_e($why) ?></p>
                                </div>
                            </div>
                        <?php endif; ?>
                        <?php if ($tradeoff !== ''): ?>
                            <div class="col-md-6">
                                <div class="bg-color-gray-50 border border-color p-3 rounded-3 h-100">
                                    <p class="text-lg fw-700 color-content mb-1">Tradeoff to know</p>
                                    <p class="text-sm color-muted"><?= cmp_e($tradeoff) ?></p>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                    <?php if (!empty($discount)): ?>
                        <div class="price-note">✓ <?= cmp_e($discount) ?> — a good time to buy</div>
                    <?php endif; ?>
                    <div class="row g-2 mb-0">
                        <div class="col-md-6">
                            <a href="<?= cmp_e($url) ?>" class="btn-amazon" target="_blank" rel="noopener noreferrer">View on <?= cmp_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"><?= cmp_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>
