<?php

$file = __DIR__ . '/data1.json';
$items = [];
if (file_exists($file)) {
  $json = file_get_contents($file);
  $items = json_decode($json, true) ?: [];
}

$latest = array_slice(array_reverse($items), 0, 4);

function h($s) { return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }
?>
<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<title>Posting-Vorschau (responsive mit Caption)</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<style>
  :root {
    --gap: 12px;
    --radius: 12px;
    --shadow: 0 2px 8px rgba(0,0,0,.08);
  }
  * { box-sizing: border-box; }
  html, body {
    margin: 0;
    padding: 0;
    background: #c7b9d0;
    font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
    color: #222;
  }

  /* Responsive Grid */
  .gallery {
    display: grid;
    grid-template-columns: 1fr;
    gap: var(--gap);
    padding: var(--gap);
  }
  @media (min-width: 640px) {
    .gallery { grid-template-columns: repeat(2, 1fr); }
  }
  @media (min-width: 900px) {
    .gallery { grid-template-columns: repeat(3, 1fr); }
  }
  @media (min-width: 1200px) {
    .gallery { grid-template-columns: repeat(4, 1fr); }
  }

  .card {
    background: #fafafa;
    border-radius: var(--radius);
    box-shadow: var(--shadow);
    overflow: hidden;
    display: flex;
    flex-direction: column;
    transition: transform 0.2s ease;
  }

  .card:hover {
    transform: scale(1.02);
  }

  .media {
    width: 100%;
    background: #ddd;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .media img,
  .media video {
    display: block;
    max-width: 100%;
    height: auto;
  }

  .caption {
    padding: 10px;
    font-size: 0.9rem;
    line-height: 1.4;
    text-align: center;
    color: #333;
    background: #fff;
  }

  .empty {
    padding: 2rem;
    text-align: center;
    color: #666;
    font-style: italic;
  }
</style>
</head>
<body>
  <div class="gallery">
    <?php if (!$latest): ?>
      <div class="empty">Noch keine Beiträge vorhanden.</div>
    <?php else: ?>
      <?php foreach ($latest as $item): ?>
        <div class="card">
          <div class="media">
            <?php if (($item['type'] ?? '') === 'video'): ?>
              <video src="<?=h($item['file'])?>" controls playsinline></video>
            <?php else: ?>
              <img src="<?=h($item['file'])?>" alt="<?=h($item['caption'])?>">
            <?php endif; ?>
          </div>
          <div class="caption"><?=h($item['caption'])?></div>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>
</body>
</html>