<?php
$variation = 'comparison';

/** Expects $data as already-decoded category JSON. */

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);
$products    = is_array($data['products'] ?? null) ? $data['products'] : [];
$pageTitle   = 'rateit.com – ' . $subcategory . ' Comparison';

$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($pageTitle) ?></title>
  <link rel="preconnect" href="https://fonts.googleapis.com" />
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,400;0,500;0,600;1,400&display=swap" />
  <link rel="stylesheet" href="style.css" />
</head>
<body class="comparison-theme">
  <header class="topbar">
    <a href="../index.html" class="brand"><span class="brand-store"><?= cmp_e($brand) ?></span></a>
    <span class="state-pill"><?= cmp_e($subcategory) ?></span>
  </header>

  <main class="page-shell">
    <section class="page-header" aria-label="Category overview">
      <?php if ($updated !== ''): ?>
        <p class="page-eyebrow">Updated <?= cmp_e($updated) ?></p>
      <?php endif; ?>
      <h1 class="page-title"><?= cmp_e($heroTitle) ?></h1>
      <p class="page-intro">Price, footprint, rating, and standout features — lined up so you can pick the right <?= cmp_e(strtolower($subcategory)) ?> at <?= cmp_e($brand) ?>.</p>
    </section>

    <div class="compare-legend" aria-hidden="true">
      <span><i class="dot gold"></i> Category winner</span>
      <span><i class="dot win"></i> Best score in column</span>
    </div>

    <section class="compare-table-wrap" aria-label="<?= cmp_e($subcategory) ?> comparison table">
      <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):
              $rank = $index + 1;
              $isWinner = $index === $winnerIndex;
              $name = $product['name'] ?? 'Untitled product';
              $image = $product['image_url'] ?? '';
              $url = $product['retailer_url'] ?? '#';
              $price = $product['price'] ?? '';
              $listPrice = $product['list_price'] ?? null;
              $discount = $product['discount'] ?? null;
              $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; ?>
                <div>
                  <p class="cell-name"><span class="cell-rank"><?= (int) $rank ?></span> <?= cmp_e($name) ?></p>
                  <?php if ($isWinner && $bestFor !== ''): ?>
                    <span class="winner-tag"><?= cmp_e($bestFor) ?></span>
                  <?php endif; ?>
                </div>
              </div>
            </td>
            <td class="cell-score<?= $isBestPrice ? ' best' : '' ?>">
              <?php if ($price !== ''): ?>
                <span class="cell-price"><?= cmp_e($price) ?></span>
                <?php if (!empty($listPrice)): ?>
                  <span class="list-strike"><?= cmp_e($listPrice) ?></span>
                <?php endif; ?>
                <?php if (!empty($discount)): ?>
                  <span class="discount-badge"><?= cmp_e($discount) ?></span>
                <?php endif; ?>
              <?php else: ?>
                —
              <?php endif; ?>
            </td>
            <td><?= $bestFor !== '' ? cmp_e($bestFor) : '—' ?></td>
            <td class="cell-score<?= $isBestRating ? ' best' : '' ?>"><?= $rating !== '' ? cmp_e($rating) . '★' : '—' ?></td>
            <td class="cell-score<?= $isBestReviews ? ' 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>
    </section>

    <section class="compare-cards" aria-label="Detailed comparison cards">
      <?php foreach ($products as $index => $product):
          $rank = $index + 1;
          $isWinner = $index === $winnerIndex;
          $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'] ?? '';
          $chips = is_array($product['chips'] ?? null) ? $product['chips'] : [];
          $summary = $product['why_it_stands_out'] ?? ($product['summary_short'] ?? '');
          $highlight = $chips[0] ?? ($product['certification'] ?? '—');
          $tradeoff = $product['tradeoff_note'] ?? '';
      ?>
      <article class="compare-card<?= $isWinner ? ' is-winner' : '' ?>">
        <div class="compare-card-media">
          <span class="compare-rank"><?= (int) $rank ?></span>
          <a href="<?= cmp_e($url) ?>" target="_blank" rel="noopener noreferrer">
            <?php if ($image !== ''): ?>
              <img src="<?= cmp_e($image) ?>" alt="<?= cmp_e($name) ?>" />
            <?php endif; ?>
          </a>
        </div>
        <div>
          <?php if ($bestFor !== ''): ?>
            <span class="card-badge<?= $isWinner ? ' win' : '' ?>"><?= cmp_e($bestFor) ?></span>
          <?php endif; ?>
          <h3><?= cmp_e($name) ?></h3>
          <?php if ($summary !== ''): ?>
            <p><?= cmp_e($summary) ?></p>
          <?php endif; ?>
          <dl class="spec-grid">
            <div class="spec-item">
              <dt>Price</dt>
              <dd>
                <?= $price !== '' ? cmp_e($price) : '—' ?>
                <?php if (!empty($listPrice)): ?>
                  <span class="list-strike"><?= cmp_e($listPrice) ?></span>
                <?php endif; ?>
                <?php if (!empty($discount)): ?>
                  <span class="discount-badge"><?= cmp_e($discount) ?></span>
                <?php endif; ?>
              </dd>
            </div>
            <div class="spec-item">
              <dt>Rating</dt>
              <dd><?= cmp_e(trim($rating . ($reviews !== '' ? ' / ' . $reviews . ' reviews' : ''))) ?: '—' ?></dd>
            </div>
            <div class="spec-item">
              <dt>Standout</dt>
              <dd><?= cmp_e($highlight) ?></dd>
            </div>
          </dl>
          <?php if ($chips): ?>
            <ul class="card-chips">
              <?php foreach ($chips as $chip): ?>
                <li><?= cmp_e($chip) ?></li>
              <?php endforeach; ?>
            </ul>
          <?php endif; ?>
          <?php if ($tradeoff !== ''): ?>
            <p class="tradeoff-note"><?= cmp_e($tradeoff) ?></p>
          <?php endif; ?>
          <a class="card-cta" href="<?= cmp_e($url) ?>" target="_blank" rel="noopener noreferrer">Shop at <?= cmp_e($brand) ?> →</a>
        </div>
      </article>
      <?php endforeach; ?>
    </section>
  </main>

  <footer class="site-footer">
    <p>© <?= date('Y') ?> <?= cmp_e($brand) ?></p>
  </footer>
</body>
</html>


