<?php

require __DIR__ . '/../bootstrap.php';

use KeyLair\Auth;
use KeyLair\ClaimService;
use KeyLair\Database;
use KeyLair\Helpers;
use KeyLair\I18n;
use KeyLair\PageStyle;
use KeyLair\Settings;

Auth::requireLogin();

/**
 * The claim-page mockups below need something to put in the "product
 * name" spot -- real products if any have actually been created (so the
 * preview looks like this install's own catalog, not a stock demo), or
 * else a couple of Secret Item Games' own real titles instead of an
 * invented placeholder game, so a brand-new install's preview still
 * looks like something real.
 */
function preview_sample_products(): array
{
    $rows = Database::connection()
        ->query('SELECT id, name, cover_image_path FROM products ORDER BY created_at DESC LIMIT 3')
        ->fetchAll();
    if (empty($rows)) {
        $rows = [
            ['id' => null, 'name' => 'Family Bowling', 'cover_image_path' => null],
            ['id' => null, 'name' => 'Paperman: Adventure Delivered', 'cover_image_path' => null],
        ];
    }
    // The first row's "1 / 5" matches the product-page mockup's own claims
    // bar exactly, since clicking through from here lands on that same mock.
    $statusLabels = ['1 / 5 claimed', '0 / 1 claimed', 'All keys claimed'];
    foreach ($rows as $i => &$row) {
        $row['status_label'] = $statusLabels[$i % count($statusLabels)];
        $row['done'] = $row['status_label'] === 'All keys claimed';
    }
    unset($row);
    return $rows;
}

$key = $_GET['key'] ?? '';
if (!PageStyle::isValidKey($key)) {
    http_response_code(400);
    die(I18n::t('preview.unknown_page'));
}

// ?theme=X previews a specific built-in (or Custom) frontend theme instead
// of whichever page-specific draft/active CSS would normally show —
// used by admin/design.php's Theme panel "Preview" links, so an admin can
// see what a theme actually looks like before switching the whole site
// to it. Not valid for the admin-panel-only keys, which don't have a
// separate theme preview (the backend theme is personal and applies the
// moment it's picked).
$previewTheme = $_GET['theme'] ?? null;
if ($previewTheme !== null && !in_array($previewTheme, Settings::THEMES, true)) {
    $previewTheme = null;
}

// Cache-bust so a just-uploaded draft shows up immediately in this preview tab.
$cssVersion = time();
function preview_css(string $key, int $v, ?string $previewTheme = null): string
{
    // These two modes are mutually exclusive in css.php ("show my pending
    // draft" vs. "resolve as if this theme were active"), so only ever
    // send one: a theme preview skips ?preview=1 entirely rather than
    // trying to combine them.
    if ($previewTheme !== null) {
        return '/assets/css/' . $key . '.css?preview_theme=' . urlencode($previewTheme) . '&v=' . $v;
    }
    return '/assets/css/' . $key . '.css?preview=1&v=' . $v;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= Helpers::e(sprintf(I18n::t('preview.page_title'), PageStyle::PAGES[$key])) ?></title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500;600;700&family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@500;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="<?= preview_css('tokens', $cssVersion, $previewTheme) ?>">
<?php if ($key !== 'tokens'): ?>
<link rel="stylesheet" href="<?= preview_css($key, $cssVersion, $previewTheme) ?>">
<?php endif; ?>
<style>
  .__preview-banner{
    position:fixed; top:0; left:0; right:0; z-index:999;
    background:#000; color:#94c93d; font-family:'JetBrains Mono',monospace;
    font-size:11.5px; letter-spacing:0.06em; text-transform:uppercase;
    text-align:center; padding:8px; border-bottom:1px solid #2a3947;
  }
  body{padding-top:34px;}
</style>
</head>
<body>
<div class="__preview-banner"><?= $previewTheme !== null ? sprintf(I18n::t('preview.banner_theme_preview'), Helpers::e(ucfirst($previewTheme))) : I18n::t('preview.banner_preview_mode') ?></div>

<?php if ($key === 'tokens'): ?>
  <div style="padding:40px 24px; max-width:720px; margin:0 auto; font-family:var(--font-body); color:var(--text-primary); background:var(--bg-void);">
    <h1 style="font-family:var(--font-display); font-size:26px;">Design tokens</h1>
    <p style="color:var(--text-muted); font-size:14px; margin-bottom:24px;">These colors and fonts are shared across every page. This preview shows their effect in isolation.</p>
    <div style="display:flex; gap:12px; flex-wrap:wrap; margin-bottom:24px;">
      <?php foreach (['--bg-panel','--signal','--key-gold','--danger','--text-primary','--text-muted'] as $var): ?>
        <div style="width:100px;">
          <div style="height:60px; border-radius:10px; background:var(<?= $var ?>); border:1px solid var(--line);"></div>
          <p style="font-family:var(--font-mono); font-size:10px; color:var(--text-faint); margin:6px 0 0;"><?= $var ?></p>
        </div>
      <?php endforeach; ?>
    </div>
    <p style="font-family:var(--font-display); font-size:22px; margin:0 0 6px;">Display heading — Space Grotesk</p>
    <p style="font-family:var(--font-body); font-size:14px; color:var(--text-muted); margin:0 0 6px;">Body text — Inter — the quick brown fox jumps over the lazy dog.</p>
    <p style="font-family:var(--font-mono); font-size:13px; color:var(--key-gold); margin:0;">ASHF-3X9K-QP2M-7RT4 — JetBrains Mono</p>
  </div>

<?php elseif ($key === 'claim-overview'):
  $previewProducts = preview_sample_products();
  $productPagePreviewUrl = 'preview.php?key=product-page' . ($previewTheme !== null ? '&theme=' . urlencode($previewTheme) : '');
?>
  <div class="page" style="margin:0 auto;">
    <div class="brandbar"><?= \KeyLair\Settings::brandIcon() ?>Key Lair · Review Access</div>
    <div class="intro">
      <h1>Your review keys</h1>
      <p class="subtitle">This link grants access to keys for the titles below. Pick a product to choose your platform and claim your key.</p>
    </div>
    <div class="product-list">
      <?php foreach ($previewProducts as $p): ?>
      <a class="product-row" href="<?= Helpers::e($productPagePreviewUrl) ?>">
        <div class="row-thumb"><?php if ($p['cover_image_path']): ?><img src="/uploads/products/<?= Helpers::e($p['cover_image_path']) ?>" alt=""><?php endif; ?></div>
        <div class="row-body"><p class="row-title"><?= Helpers::e($p['name']) ?></p><span class="row-status<?= $p['done'] ? ' done' : '' ?>"><?= Helpers::e($p['status_label']) ?></span></div>
        <svg class="row-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 6l6 6-6 6"/></svg>
      </a>
      <?php endforeach; ?>
    </div>
    <footer>Having trouble? Contact the person who sent you this link.<br>Powered by <a href="https://www.keylair.com" target="_blank" rel="noopener">Key Lair</a></footer>
  </div>

<?php elseif ($key === 'product-page'):
  $previewProduct = preview_sample_products()[0];
  $previewProductName = $previewProduct['name'];
  $claimOverviewPreviewUrl = 'preview.php?key=claim-overview' . ($previewTheme !== null ? '&theme=' . urlencode($previewTheme) : '');
  // A real product's own screenshots/trailer if it has any -- same
  // builder the real claim page uses -- otherwise the placeholder
  // trailer + numbered screenshots below stay as they were.
  $previewMediaItems = $previewProduct['id'] !== null
      ? ClaimService::buildMediaShowcase(ClaimService::mediaForProduct((int) $previewProduct['id']), $previewProduct['cover_image_path'])
      : [];
?>
  <div class="page" style="margin:0 auto;">
    <div class="crumb"><a href="<?= Helpers::e($claimOverviewPreviewUrl) ?>">&larr; All products for this link</a></div>
    <div class="brandbar"><?= \KeyLair\Settings::brandIcon() ?>Key Lair · Review Access</div>
    <?php if (!empty($previewMediaItems)): ?>
    <div class="media-showcase">
      <div class="media-main <?= $previewMediaItems[0]['type'] === 'shot' ? 'is-shot' : '' ?>" id="preview-media-main">
        <?php if ($previewMediaItems[0]['type'] === 'video'): ?>
          <iframe src="<?= Helpers::e($previewMediaItems[0]['src']) ?>" style="width:100%;height:100%;border:0;border-radius:inherit;position:relative;z-index:1;" allowfullscreen loading="lazy"></iframe>
        <?php else: ?>
          <img src="<?= Helpers::e($previewMediaItems[0]['src']) ?>" alt="" style="width:100%;height:100%;object-fit:cover;border-radius:inherit;position:relative;z-index:1;">
        <?php endif; ?>
      </div>
      <div class="media-thumbs">
        <?php foreach ($previewMediaItems as $i => $item): ?>
          <div class="thumb <?= $item['type'] ?> <?= $i === 0 ? 'active' : '' ?>" data-type="<?= $item['type'] ?>" data-src="<?= Helpers::e($item['src']) ?>" onclick="previewShowMedia(this)">
            <?php if ($item['type'] === 'video'): ?>
              <span class="thumb-play"><svg viewBox="0 0 24 24" fill="#17212e"><path d="M8 5v14l11-7z"/></svg></span>
            <?php else: ?>
              <img src="<?= Helpers::e($item['src']) ?>" alt="" style="width:100%;height:100%;object-fit:cover;border-radius:inherit;">
            <?php endif; ?>
          </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php else: ?>
    <div class="media-showcase">
      <div class="media-main" id="preview-media-main"><span class="play-badge"><svg viewBox="0 0 24 24" fill="#17212e"><path d="M8 5v14l11-7z"/></svg></span><span class="media-main-label">Trailer</span></div>
      <div class="media-thumbs">
        <div class="thumb video active" data-type="video" data-label="Trailer" onclick="previewShowMedia(this)"><span class="thumb-play"><svg viewBox="0 0 24 24" fill="#17212e"><path d="M8 5v14l11-7z"/></svg></span></div>
        <div class="thumb" data-type="shot" data-label="Screenshot 01" onclick="previewShowMedia(this)"><span class="thumb-label">01</span></div>
        <div class="thumb" data-type="shot" data-label="Screenshot 02" onclick="previewShowMedia(this)"><span class="thumb-label">02</span></div>
        <div class="thumb" data-type="shot" data-label="Screenshot 03" onclick="previewShowMedia(this)"><span class="thumb-label">03</span></div>
      </div>
    </div>
    <?php endif; ?>
    <div class="hero"><h1><?= Helpers::e($previewProductName) ?></h1></div>
    <div class="text-block">
      <p class="text-block-label">About this key</p>
      <p>Thanks for checking out <strong><?= Helpers::e($previewProductName) ?></strong>! This is a review build of the full game.</p>
    </div>
    <div class="claims-bar">
      <span class="claims-label">Claims used</span>
      <div class="claims-track"><div class="claims-fill" id="preview-claims-fill" style="width:20%"></div></div>
      <span class="claims-count" id="preview-claims-count">1 / 5</span>
    </div>
    <div id="preview-reveal-container">
    <div class="reveal show">
      <div class="reveal-top"><span class="reveal-check"><svg viewBox="0 0 24 24" fill="none" stroke="#17212e" stroke-width="3"><path d="M4 12l5 5L20 6"/></svg></span><span class="reveal-title">Your Steam key is ready</span></div>
      <div class="readout"><span class="readout-code">ASHF-3X9K-QP2M-7RT4</span><button class="copy-btn" onclick="previewCopyCode(this)">Copy key</button></div>
      <p class="reveal-note">This key can only be redeemed once.</p>
    </div>
    </div>
    <div id="preview-platform-section">
    <p class="section-label">Choose your platform</p>
    <?php
    // Mirrors the real claim page's markup (public/product.php +
    // Platform::groupForClaimPage()) -- a multi-region family collapses
    // into one expandable group, a lone platform renders as its own tile
    // and spans the full row when nothing sits beside it (see .tile-full
    // in product-page.css) -- so this preview actually demonstrates both
    // patterns instead of just two flat tiles.
    $steamIcon = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="13" r="7.5"/><circle cx="8.5" cy="9" r="2.6"/><circle cx="8.5" cy="9" r="0.6" fill="currentColor" stroke="none"/><path d="M8.5 9L14 14.5"/><circle cx="14" cy="14.5" r="1.6"/><circle cx="14" cy="14.5" r="0.5" fill="currentColor" stroke="none"/></svg>';
    $storeIcon = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M4 9l1-5h14l1 5"/><rect x="4" y="9" width="16" height="11" rx="1"/><path d="M9 13v4M15 13v4"/></svg>';
    $xboxIcon = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.3"><circle cx="12" cy="12" r="9.5"/><path d="M7 7l10 10" stroke-width="2.1" stroke-linecap="round"/><path d="M17 7L7 17" stroke-width="2.1" stroke-linecap="round"/></svg>';
    $switchIcon = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><rect x="2.5" y="5" width="6" height="14" rx="2.5"/><rect x="15.5" y="5" width="6" height="14" rx="2.5"/><rect x="8.5" y="6.5" width="7" height="11" rx="1"/><circle cx="5.5" cy="9" r="0.9" fill="currentColor" stroke="none"/><circle cx="18.5" cy="9" r="0.9" fill="currentColor" stroke="none"/><circle cx="18.5" cy="15" r="0.9" fill="currentColor" stroke="none"/></svg>';
    $psIcon = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M6 8h12a3 3 0 013 3c0 1.5-.5 6-2 8a2 2 0 01-3.2.4L13 16.5a1.5 1.5 0 00-2 0L8.2 19.4A2 2 0 015 19c-1.5-2-2-6.5-2-8a3 3 0 013-3z"/><circle cx="9" cy="12" r="0.8" fill="currentColor" stroke="none"/><circle cx="15" cy="12" r="0.8" fill="currentColor" stroke="none"/></svg>';
    ?>
    <div class="grid">
      <details class="tile-group" open>
        <summary class="tile-group-summary">
          <span class="tile-icon"><?= $steamIcon ?></span>
          <span class="tile-info"><span class="tile-name">PC</span><span class="tile-status">Available</span></span>
          <svg class="group-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 9l6 6 6-6"/></svg>
        </summary>
        <div class="tile-group-body">
          <div class="tile" onclick="previewClaimPlatform(this, 'Steam')"><span class="notch"></span><span class="tile-icon"><?= $steamIcon ?></span><span class="tile-info"><span class="tile-name">Steam</span><span class="tile-status">Available</span></span></div>
          <div class="tile" onclick="previewClaimPlatform(this, 'GOG')"><span class="notch"></span><span class="tile-icon"><?= $storeIcon ?></span><span class="tile-info"><span class="tile-name">GOG</span><span class="tile-status">Available</span></span></div>
        </div>
      </details>
      <div class="tile tile-full" onclick="previewClaimPlatform(this, 'Xbox/Microsoft Store')"><span class="notch"></span><span class="tile-icon"><?= $xboxIcon ?></span><span class="tile-info"><span class="tile-name">Xbox/Microsoft Store</span><span class="tile-status">Available</span></span></div>
      <details class="tile-group">
        <summary class="tile-group-summary">
          <span class="tile-icon"><?= $switchIcon ?></span>
          <span class="tile-info"><span class="tile-name">Nintendo Switch 2</span><span class="tile-status">Available</span></span>
          <svg class="group-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 9l6 6 6-6"/></svg>
        </summary>
        <div class="tile-group-body">
          <div class="tile" onclick="previewClaimPlatform(this, 'Nintendo Switch 2 (EU)')"><span class="notch"></span><span class="tile-icon"><?= $switchIcon ?></span><span class="tile-info"><span class="tile-name">Nintendo Switch 2 (EU)</span><span class="tile-status">Available</span></span></div>
          <div class="tile" onclick="previewClaimPlatform(this, 'Nintendo Switch 2 (US)')"><span class="notch"></span><span class="tile-icon"><?= $switchIcon ?></span><span class="tile-info"><span class="tile-name">Nintendo Switch 2 (US)</span><span class="tile-status">Available</span></span></div>
        </div>
      </details>
      <details class="tile-group">
        <summary class="tile-group-summary">
          <span class="tile-icon"><?= $switchIcon ?></span>
          <span class="tile-info"><span class="tile-name">Nintendo Switch</span><span class="tile-status">Available</span></span>
          <svg class="group-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 9l6 6 6-6"/></svg>
        </summary>
        <div class="tile-group-body">
          <div class="tile" onclick="previewClaimPlatform(this, 'Nintendo Switch (EU)')"><span class="notch"></span><span class="tile-icon"><?= $switchIcon ?></span><span class="tile-info"><span class="tile-name">Nintendo Switch (EU)</span><span class="tile-status">Available</span></span></div>
          <div class="tile disabled"><span class="notch"></span><span class="tile-icon"><?= $switchIcon ?></span><span class="tile-info"><span class="tile-name">Nintendo Switch (US)</span><span class="tile-status">Sold out</span></span></div>
        </div>
      </details>
      <details class="tile-group">
        <summary class="tile-group-summary">
          <span class="tile-icon"><?= $psIcon ?></span>
          <span class="tile-info"><span class="tile-name">PlayStation 5</span><span class="tile-status">Available</span></span>
          <svg class="group-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 9l6 6 6-6"/></svg>
        </summary>
        <div class="tile-group-body">
          <div class="tile" onclick="previewClaimPlatform(this, 'PlayStation 5 (EU)')"><span class="notch"></span><span class="tile-icon"><?= $psIcon ?></span><span class="tile-info"><span class="tile-name">PlayStation 5 (EU)</span><span class="tile-status">Available</span></span></div>
          <div class="tile" onclick="previewClaimPlatform(this, 'PlayStation 5 (US)')"><span class="notch"></span><span class="tile-icon"><?= $psIcon ?></span><span class="tile-info"><span class="tile-name">PlayStation 5 (US)</span><span class="tile-status">Available</span></span></div>
        </div>
      </details>
      <details class="tile-group disabled">
        <summary class="tile-group-summary">
          <span class="tile-icon"><?= $psIcon ?></span>
          <span class="tile-info"><span class="tile-name">PlayStation 4</span><span class="tile-status">Sold out</span></span>
          <svg class="group-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 9l6 6 6-6"/></svg>
        </summary>
        <div class="tile-group-body">
          <div class="tile disabled"><span class="notch"></span><span class="tile-icon"><?= $psIcon ?></span><span class="tile-info"><span class="tile-name">PlayStation 4 (EU)</span><span class="tile-status">Sold out</span></span></div>
          <div class="tile disabled"><span class="notch"></span><span class="tile-icon"><?= $psIcon ?></span><span class="tile-info"><span class="tile-name">PlayStation 4 (US)</span><span class="tile-status">Sold out</span></span></div>
        </div>
      </details>
    </div>
    </div>
    <footer>Powered by <a href="https://www.keylair.com" target="_blank" rel="noopener">Key Lair</a></footer>
  </div>

<?php elseif ($key === 'admin-dashboard'): ?>
  <div style="display:flex; min-height:100vh;">
    <aside class="sidebar">
      <div class="brand"><?= \KeyLair\Settings::brandIcon() ?>Key Lair</div>
      <nav>
        <div class="nav-item active"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><rect x="3" y="3" width="8" height="8" rx="1.5"/><rect x="13" y="3" width="8" height="8" rx="1.5"/></svg><span class="label">Dashboard</span></div>
        <div class="nav-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><rect x="4" y="9" width="16" height="10" rx="2"/></svg><span class="label">Keys</span></div>
      </nav>
      <div class="sidebar-footer"><div class="avatar"></div><div class="who"><div class="name">admin</div><div class="role">Master admin</div></div></div>
    </aside>
    <main class="main">
      <div class="topbar"><h1>Dashboard</h1><div class="campaign-select">Ashfall Chronicles <span class="badge">Active</span></div></div>
      <div class="stat-grid">
        <div class="stat-card"><div class="stat-label">Total keys</div><div class="stat-value">5,000</div></div>
        <div class="stat-card"><div class="stat-label">Remaining</div><div class="stat-value signal">3,214</div></div>
        <div class="stat-card"><div class="stat-label">Redeemed</div><div class="stat-value gold">1,786</div></div>
        <div class="stat-card"><div class="stat-label">Rate</div><div class="stat-value">35.7%</div></div>
      </div>
      <div class="panel"><p class="panel-title">Recent redemptions</p>
        <table><thead><tr><th>Creator</th><th>Platform</th><th>Time</th></tr></thead>
        <tbody><tr><td class="creator" data-label="Creator">@GamerHub</td><td data-label="Platform"><span class="plat-tag">Switch</span></td><td class="time-cell" data-label="Time">20:14</td></tr></tbody></table>
      </div>
    </main>
  </div>

<?php elseif ($key === 'admin-product-editor'): ?>
  <link rel="stylesheet" href="<?= preview_css('admin-dashboard', $cssVersion) ?>">
  <div style="display:flex; min-height:100vh;">
    <aside class="sidebar">
      <div class="brand"><?= \KeyLair\Settings::brandIcon() ?>Key Lair</div>
      <nav><div class="nav-item active"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M4 7l8-4 8 4-8 4-8-4z"/></svg><span class="label">Products</span></div></nav>
    </aside>
    <main class="main">
      <div class="topbar"><h1>Edit product</h1><span class="status-pill">Active</span></div>
      <div class="form-shell">
        <div class="form-section">
          <p class="form-section-title">Basics</p>
          <div class="field"><label>Product name</label><input type="text" value="Ashfall Chronicles" readonly></div>
        </div>
        <div class="form-section">
          <p class="form-section-title">Intro text</p>
          <div class="rte"><div class="rte-toolbar"><span class="rte-btn"><b>B</b></span><span class="rte-btn"><i>I</i></span></div><div class="rte-body">Sample intro text.</div></div>
        </div>
      </div>
    </main>
  </div>
<?php endif; ?>
<?php if ($key === 'product-page'): ?>
<script>
  // Same interaction as the real claim page's showMedia() (public/product.php)
  // -- swap which thumbnail is active and reflect that in the main showcase.
  // A thumb with a real data-src (this product has actual screenshots/a
  // trailer) swaps in the real image/iframe, same as the real page; one
  // without (nothing uploaded, so it's just a data-label) swaps in the
  // same placeholder text it always has.
  function previewShowMedia(el){
    document.querySelectorAll('.thumb').forEach(t => t.classList.remove('active'));
    el.classList.add('active');
    var main = document.getElementById('preview-media-main');
    var isVideo = el.dataset.type === 'video';
    var src = el.dataset.src;
    main.classList.toggle('is-shot', !isVideo);
    if (src) {
      main.innerHTML = isVideo
        ? '<iframe src="'+src+'" style="width:100%;height:100%;border:0;border-radius:inherit;position:relative;z-index:1;" allowfullscreen loading="lazy"></iframe>'
        : '<img src="'+src+'" alt="" style="width:100%;height:100%;object-fit:cover;border-radius:inherit;position:relative;z-index:1;">';
    } else {
      main.innerHTML = isVideo
        ? '<span class="play-badge"><svg viewBox="0 0 24 24" fill="#17212e"><path d="M8 5v14l11-7z"/></svg></span><span class="media-main-label">' + el.dataset.label + '</span>'
        : '<span class="media-main-label">' + el.dataset.label + '</span>';
    }
  }
  function previewCopyCode(btn){
    var code = btn.previousElementSibling.textContent;
    navigator.clipboard?.writeText(code);
    var original = btn.textContent;
    btn.textContent = 'Copied';
    setTimeout(function(){ btn.textContent = original; }, 1400);
  }

  // Simulates actually claiming a key -- purely client-side, nothing is
  // sent to the server or persisted anywhere, so a reload always starts
  // back over at the same "1 / 5, one Steam key already claimed" state
  // this page always renders. Stops once the claims bar is full, same
  // as the real claim page hiding "Choose your platform" entirely once
  // claimsRemaining hits 0 (see public/product.php).
  var previewClaimsUsed = 1;
  var previewClaimsMax = 5;
  function previewFakeKeyCode(){
    var alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    var groups = [];
    for (var g = 0; g < 4; g++) {
      var group = '';
      for (var c = 0; c < 4; c++) {
        group += alphabet[Math.floor(Math.random() * alphabet.length)];
      }
      groups.push(group);
    }
    return groups.join('-');
  }
  function previewClaimPlatform(el, label){
    if (el.classList.contains('disabled') || previewClaimsUsed >= previewClaimsMax) {
      return;
    }
    previewClaimsUsed++;
    document.getElementById('preview-claims-fill').style.width = Math.min(100, Math.round(previewClaimsUsed / previewClaimsMax * 100)) + '%';
    document.getElementById('preview-claims-count').textContent = previewClaimsUsed + ' / ' + previewClaimsMax;

    var reveal = document.createElement('div');
    reveal.className = 'reveal show';
    reveal.innerHTML = '<div class="reveal-top"><span class="reveal-check"><svg viewBox="0 0 24 24" fill="none" stroke="#17212e" stroke-width="3"><path d="M4 12l5 5L20 6"/></svg></span><span class="reveal-title">Your ' + label + ' key is ready</span></div>'
      + '<div class="readout"><span class="readout-code">' + previewFakeKeyCode() + '</span><button class="copy-btn" onclick="previewCopyCode(this)">Copy key</button></div>'
      + '<p class="reveal-note">This key can only be redeemed once.</p>';
    document.getElementById('preview-reveal-container').appendChild(reveal);

    if (previewClaimsUsed >= previewClaimsMax) {
      var section = document.getElementById('preview-platform-section');
      if (section) {
        section.remove();
      }
    }
  }
</script>
<?php endif; ?>
</body>
</html>
