<?php
$pageTitle   = 'Community — dispelled.ca';
$currentPage = 'community';

require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/reddit.php';

$SUBREDDITS = [
    ['id' => 'linux',       'label' => 'r/linux'],
    ['id' => 'programming', 'label' => 'r/programming'],
    ['id' => 'netsec',      'label' => 'r/netsec'],
    ['id' => 'sysadmin',    'label' => 'r/sysadmin'],
    ['id' => 'opensource',  'label' => 'r/opensource'],
];

$filter = $_GET['sub'] ?? 'all';
if (!in_array($filter, array_merge(['all'], array_column($SUBREDDITS, 'id')))) {
    $filter = 'all';
}

$allItems = getRedditPosts();

$items = ($filter === 'all')
    ? $allItems
    : array_values(array_filter($allItems, fn($i) => $i['subreddit'] === $filter));

$SUB_COLORS = [
    'linux'       => '#0dd3bb',
    'programming' => '#ff6314',
    'netsec'      => '#00b4d8',
    'sysadmin'    => '#a855f7',
    'opensource'  => '#4caf50',
];

function human_time_diff_php(string $ts): string {
    $diff = time() - strtotime($ts);
    if ($diff < 0)     return 'just now';
    if ($diff < 60)    return $diff . ' sec';
    if ($diff < 3600)  return floor($diff / 60) . ' min';
    if ($diff < 86400) return floor($diff / 3600) . ' hr';
    return floor($diff / 86400) . ' d';
}

require_once __DIR__ . '/includes/header.php';
?>

<div class="page-header-row">
  <h1 class="page-title" style="margin-bottom:0">Community</h1>
  <div class="filter-bar" style="margin-top:0">
    <a href="?sub=all" class="filter-btn <?= $filter === 'all' ? 'active' : '' ?>">All</a>
    <?php foreach ($SUBREDDITS as $sub): ?>
      <a href="?sub=<?= $sub['id'] ?>" class="filter-btn <?= $filter === $sub['id'] ? 'active' : '' ?>">
        <?= htmlspecialchars($sub['label']) ?>
      </a>
    <?php endforeach ?>
  </div>
</div>

<?php if (empty($items)): ?>
  <p class="empty-msg">No posts found.</p>
<?php else: ?>
<div class="feed-list feed-timeline">
  <?php foreach ($items as $item):
    $color = $SUB_COLORS[$item['subreddit']] ?? '#4a9eff';
    $ago   = human_time_diff_php($item['publishedAt']);
  ?>
  <div class="feed-item">
    <div class="feed-dot" style="background:<?= $color ?>"></div>
    <div class="feed-body">
      <h2>
        <a href="<?= htmlspecialchars($item['url']) ?>" target="_blank" rel="noreferrer">
          <?= htmlspecialchars($item['title']) ?>
        </a>
      </h2>
      <div class="feed-meta">
        <span class="source-badge" style="background:<?= $color ?>22;color:<?= $color ?>">
          <?= htmlspecialchars($item['subredditLabel']) ?>
        </span>
        <span class="feed-time"><?= $ago ?> ago</span>
      </div>
      <?php if (!empty($item['description'])): ?>
        <p class="feed-desc"><?= htmlspecialchars($item['description']) ?></p>
      <?php endif ?>
    </div>
  </div>
  <?php endforeach ?>
</div>
<?php endif ?>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
