<?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; ?>

  <!-- Stack Overflow Header & Actions -->
  <div class="container" style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:1rem; margin-block-end:1rem;">
    <h1 style="margin:0; font-size:1.625rem; font-weight:600;"><?= quaeriva_t($translator, 'questions.latest') ?></h1>
    <div style="display:flex; gap:0.5rem;">
      <a class="button button-small" href="<?= quaeriva_escape(quaeriva_url('ask')) ?>" style="background-color:#0a95ff; border-color:#0a95ff; color:#fff; font-weight:600; border-radius:3px;"><?= quaeriva_t($translator, 'questions.ask') ?></a>
      <a class="button button-small button-secondary" href="<?= quaeriva_escape(quaeriva_url('d/new')) ?>" style="border-radius:3px;"><?= quaeriva_t($translator, 'topics.start') ?></a>
    </div>
  </div>

  <!-- Filter Tabs -->
  <div class="container" style="display:flex; justify-content:flex-end; margin-block-end:0.75rem;">
    <div class="community-feed-tabs" role="navigation" style="display:inline-flex; border:1px solid var(--color-border); border-radius:3px; overflow:hidden;">
      <?php foreach (['all' => 'topics.filter_all', 'questions' => 'topics.filter_questions', 'discussions' => 'topics.filter_topics', 'unanswered' => 'search.unanswered_only'] as $key => $label): ?>
        <a href="<?= quaeriva_escape(quaeriva_url('', $key === 'all' ? [] : ['feed' => $key])) ?>"<?= $activeFilter === $key ? ' aria-current="page"' : '' ?> style="padding:0.35rem 0.75rem; font-size:0.8125rem; text-decoration:none; color:var(--color-text); <?= $activeFilter === $key ? 'background-color:#e3e6e8; font-weight:700;' : 'background-color:#fff;' ?>">
          <?= quaeriva_t($translator, $label) ?>
        </a>
      <?php endforeach; ?>
    </div>
  </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">
          <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'] ?? ''));
        $userId = (int) ($item['author_user_id'] ?? 0);
        $avatar = trim((string) ($item['author_avatar_url'] ?? ''));
        if ($avatar === '' && $author !== '') {
          $avatar = quaeriva_default_avatar_url($userId);
        }
        $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']);
        $itemUrl = $isQuestion
          ? quaeriva_question_url((string) ($item['slug'] ?? ''), (int) ($item['id'] ?? 0))
          : quaeriva_url('d/' . rawurlencode((string) ($item['slug'] ?? '')));
      ?>
        <article class="nexus-row">
          <!-- Stack Overflow 3-Box Stats Column -->
          <div class="nexus-stats-col">
            <span class="nexus-stat-item">
              <strong><?= $isQuestion ? $votesCount : $commentsCount ?></strong> <?= quaeriva_t($translator, $isQuestion ? 'common.votes' : 'topics.comments') ?>
            </span>
            <?php if ($isQuestion): ?>
              <span class="nexus-stat-item nexus-stat-answers <?= $hasBestAnswer ? 'has-best-answer' : ($answersCount > 0 ? 'has-answers' : '') ?>">
                <?php if ($hasBestAnswer): ?>✔ <?php endif; ?><strong><?= $answersCount ?></strong> <?= quaeriva_t($translator, 'common.answers') ?>
              </span>
            <?php endif; ?>
            <span class="nexus-stat-item" style="color:#838c95;">
              <bdi><?= $viewsCount ?></bdi> <?= quaeriva_t($translator, 'common.views') ?>
            </span>
          </div>

          <!-- Content Column -->
          <div class="nexus-content-col">
            <h3 class="nexus-title">
              <a dir="auto" href="<?= quaeriva_escape($itemUrl) ?>"><?= quaeriva_escape((string) ($item['title'] ?? '')) ?></a>
            </h3>

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

            <div class="nexus-row-footer">
              <div style="display:flex; gap:0.35rem; flex-wrap:wrap; align-items:center;">
                <?php if (trim((string) ($item['category_slug'] ?? '')) !== ''): ?>
                  <a class="nexus-tag-chip" href="<?= quaeriva_escape(quaeriva_url('c/' . rawurlencode((string) $item['category_slug']))) ?>"><?= quaeriva_escape($item['category_name'] ?? '') ?></a>
                <?php endif; ?>

                <?php if ($isQuestion && is_array($item['tags'] ?? null) && $item['tags'] !== []): ?>
                  <?php foreach (array_slice($item['tags'], 0, 4) as $tag): ?>
                    <a class="nexus-tag-chip" href="<?= quaeriva_escape(quaeriva_url('t/' . rawurlencode((string) $tag['slug']))) ?>"><?= quaeriva_escape($tag['name']) ?></a>
                  <?php endforeach; ?>
                <?php endif; ?>
              </div>

              <!-- Stack User Card -->
              <div class="nexus-user-card">
                <?php if ($avatar !== ''): ?><img src="<?= quaeriva_escape($avatar) ?>" alt="" width="18" height="18" loading="lazy"><?php endif; ?>
                <?php if ($author !== '' && $username !== ''): ?>
                  <a href="<?= quaeriva_escape(quaeriva_url('u/' . rawurlencode($username))) ?>" style="color:#0074cc; text-decoration:none;"><bdi><?= quaeriva_escape($author) ?></bdi></a>
                <?php else: ?>
                  <span><?= quaeriva_t($translator, 'common.anonymous') ?></span>
                <?php endif; ?>
                <time datetime="<?= quaeriva_escape((string) ($item['activity_at'] ?? '')) ?>"><?= quaeriva_escape(quaeriva_relative_time($item['activity_at'] ?? '', $translator)) ?></time>
              </div>
            </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; ?>
