<?php
declare(strict_types=1);
$items = is_array($communityFeed ?? null) ? $communityFeed : [];
$activeFilter = in_array(($feedFilter ?? 'all'), ['all', 'questions', 'discussions', 'unanswered'], true) ? (string) $feedFilter : 'all';
$homeSidebar = isset($renderSection) && is_callable($renderSection) ? $renderSection('home_sidebar') : '';
?>
<section class="content-section community-home" id="community-feed">
  <?php if (($submittedQuestionId ?? 0) > 0): ?>
    <div class="container"><div class="notice" role="status"><?= quaeriva_t($translator, 'questions.submission_received') ?></div></div>
  <?php endif; ?>

  <!-- Reddit-Style Quick Create Post Bar -->
  <div class="container" style="margin-block-end: 1rem;">
    <div style="display:flex; align-items:center; gap:0.75rem; background:var(--color-surface); border:1px solid var(--color-border); border-radius:var(--radius-sm); padding:0.6rem 1rem;">
      <a href="<?= quaeriva_escape(quaeriva_url('ask')) ?>" style="flex:1; background:var(--color-surface-soft); border:1px solid var(--color-border); border-radius:var(--radius-sm); padding:0.5rem 1rem; color:var(--color-muted); text-decoration:none; font-size:0.875rem;">
        <?= quaeriva_t($translator, 'questions.ask') ?>...
      </a>
      <a class="button button-small" href="<?= quaeriva_escape(quaeriva_url('ask')) ?>" style="font-weight:700;"><?= quaeriva_t($translator, 'questions.ask') ?></a>
      <a class="button button-small button-secondary" href="<?= quaeriva_escape(quaeriva_url('d/new')) ?>"><?= quaeriva_t($translator, 'topics.start') ?></a>
    </div>
  </div>

  <!-- Filter Tabs -->
  <div class="container community-feed-tabs" role="navigation" aria-label="<?= quaeriva_t($translator, 'topics.filter_all') ?>" style="margin-block-end: 1rem; display:flex; gap:0.5rem; background:var(--color-surface); border:1px solid var(--color-border); border-radius:var(--radius-sm); padding:0.5rem 0.75rem;">
    <?php foreach (['all' => 'topics.filter_all', 'questions' => 'topics.filter_questions', 'discussions' => 'topics.filter_topics', 'unanswered' => 'search.unanswered_only'] as $key => $label): ?>
      <a class="button button-small <?= $activeFilter === $key ? '' : 'button-secondary' ?>" href="<?= quaeriva_escape(quaeriva_url('', $key === 'all' ? [] : ['feed' => $key])) ?>"<?= $activeFilter === $key ? ' aria-current="page"' : '' ?> style="border:none;"><?= quaeriva_t($translator, $label) ?></a>
    <?php endforeach; ?>
  </div>

  <div class="container community-feed-grid<?= $homeSidebar !== '' ? ' has-community-sidebar' : '' ?>">
    <main class="community-feed">
      <?php if (!($dbAvailable ?? false) && $items === []): ?>
        <p class="notice notice-muted" role="status"><?= quaeriva_t($translator, 'common.database_unavailable') ?></p>
      <?php endif; ?>
      <?php if ($items === []): ?>
        <div class="empty-state" style="background:var(--color-surface); border:1px solid var(--color-border); border-radius:var(--radius-sm);">
          <span class="empty-mark" aria-hidden="true">＋</span>
          <h3><?= quaeriva_t($translator, 'common.empty_questions') ?></h3>
          <p><?= quaeriva_t($translator, 'common.empty_questions_hint') ?></p>
        </div>
      <?php endif; ?>

      <?php foreach ($items as $item):
        $isQuestion = ($item['type'] ?? 'question') === 'question';
        $author = trim((string) ($item['author_name'] ?? ''));
        $username = trim((string) ($item['author_username'] ?? ''));
        $categorySlug = trim((string) ($item['category_slug'] ?? ''));
        $categoryName = trim((string) ($item['category_name'] ?? ''));
        $votesCount = (int) ($item['votes_count'] ?? 0);
        $answersCount = (int) ($item['answers_count'] ?? 0);
        $commentsCount = (int) ($item['comments_count'] ?? 0);
        $viewsCount = (int) ($item['views_count'] ?? 0);
        $hasBestAnswer = $isQuestion && !empty($item['best_answer_id']);
        $totalReplies = $isQuestion ? $answersCount : $commentsCount;
        $itemUrl = $isQuestion
          ? quaeriva_question_url((string) ($item['slug'] ?? ''), (int) ($item['id'] ?? 0))
          : quaeriva_url('d/' . rawurlencode((string) ($item['slug'] ?? '')));
      ?>
        <article class="orbit-card">
          <!-- Reddit Vertical Vote Rail -->
          <div class="orbit-vote-rail">
            <span class="vote-icon" aria-hidden="true">▲</span>
            <strong><?= $votesCount ?></strong>
            <span class="vote-icon" aria-hidden="true">▼</span>
          </div>

          <!-- Post Content -->
          <div class="orbit-card-content">
            <div class="orbit-post-meta">
              <?php if ($categorySlug !== ''): ?>
                <a class="orbit-sub-badge" href="<?= quaeriva_escape(quaeriva_url('c/' . rawurlencode($categorySlug))) ?>">c/<?= quaeriva_escape($categoryName) ?></a>
                <span aria-hidden="true">•</span>
              <?php endif; ?>

              <span>
                <?= quaeriva_t($translator, 'common.author') ?>
                <?php if ($author !== '' && $username !== ''): ?>
                  <a class="author-inline" href="<?= quaeriva_escape(quaeriva_url('u/' . rawurlencode($username))) ?>" style="color:inherit; font-weight:600;"><bdi>u/<?= quaeriva_escape($username) ?></bdi></a>
                <?php else: ?>
                  <?= quaeriva_t($translator, 'common.anonymous') ?>
                <?php endif; ?>
              </span>

              <span aria-hidden="true">•</span>
              <time datetime="<?= quaeriva_escape((string) ($item['activity_at'] ?? '')) ?>"><?= quaeriva_escape(quaeriva_relative_time($item['activity_at'] ?? '', $translator)) ?></time>

              <?php if ($hasBestAnswer): ?>
                <span class="orbit-flair is-best"><?= quaeriva_t($translator, 'questions.best_answer') ?></span>
              <?php elseif (!$isQuestion): ?>
                <span class="orbit-flair"><?= quaeriva_t($translator, 'topics.eyebrow') ?></span>
              <?php endif; ?>
            </div>

            <h3 class="orbit-post-title">
              <a dir="auto" href="<?= quaeriva_escape($itemUrl) ?>"><?= quaeriva_escape((string) ($item['title'] ?? '')) ?></a>
            </h3>

            <p class="orbit-post-excerpt" dir="auto">
              <?= quaeriva_escape(mb_strimwidth(strip_tags((string) ($item['body'] ?? '')), 0, 190, '…', 'UTF-8')) ?>
            </p>

            <!-- Reddit Action Pills -->
            <div class="orbit-action-bar">
              <a class="orbit-pill-btn" href="<?= quaeriva_escape($itemUrl) ?>">
                💬 <bdi><?= $totalReplies ?></bdi> <?= quaeriva_t($translator, $isQuestion ? 'common.answers' : 'topics.comments') ?>
              </a>
              <span class="orbit-pill-btn">
                👁 <bdi><?= $viewsCount ?></bdi> <?= quaeriva_t($translator, 'common.views') ?>
              </span>
              <button class="orbit-pill-btn" type="button" data-share-question data-share-url="<?= quaeriva_escape($itemUrl) ?>">
                ↗ <?= quaeriva_t($translator, 'questions.share') ?>
              </button>
            </div>
          </div>
        </article>
      <?php endforeach; ?>
    </main>

    <?php if ($homeSidebar !== ''): ?>
      <aside class="community-sidebar"><?= $homeSidebar ?></aside>
    <?php endif; ?>
  </div>
</section>

<?php if (trim((string) ($widgetsHtml ?? '')) !== ''): ?>
  <?= $widgetsHtml ?>
<?php endif; ?>
