<?php
declare(strict_types=1);
$items = is_array($communityFeed ?? null) ? $communityFeed : [];
$activeFilter = in_array(($feedFilter ?? 'all'), ['all', 'questions', 'discussions', 'unanswered'], true) ? (string) $feedFilter : 'all';
$isGuest = !is_array($currentUser ?? null);
$homeSidebar = isset($renderSection) && is_callable($renderSection) ? $renderSection('home_sidebar') : '';
?>
<?php if ($isGuest): ?>
<section class="hero-section community-hero">
  <div class="container community-hero-inner">
    <div class="hero-copy">
      <p class="eyebrow"><?= quaeriva_t($translator, 'home.eyebrow') ?></p>
      <h1><?= quaeriva_t($translator, 'home.title') ?></h1>
      <p class="hero-lede"><?= quaeriva_t($translator, 'home.intro') ?></p>
    </div>
    <div class="hero-actions">
      <a class="button" href="<?= quaeriva_escape(quaeriva_url('ask')) ?>"><?= quaeriva_t($translator, 'questions.ask') ?></a>
      <a class="button button-secondary" href="<?= quaeriva_escape(quaeriva_url('d/new')) ?>"><?= quaeriva_t($translator, 'topics.start') ?></a>
    </div>
  </div>
</section>
<?php endif; ?>

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

  <div class="container community-toolbar">
    <div>
      <p class="eyebrow"><?= quaeriva_t($translator, 'home.eyebrow') ?></p>
      <h2><?= quaeriva_t($translator, 'questions.latest') ?></h2>
    </div>
    <form class="section-search" method="get" action="<?= quaeriva_escape(quaeriva_url('search')) ?>" role="search">
      <label class="visually-hidden" for="community-search"><?= quaeriva_t($translator, 'common.search') ?></label>
      <input id="community-search" name="q" type="search" dir="<?= quaeriva_escape($localeContext->htmlAttributes()['dir']) ?>" placeholder="<?= quaeriva_t($translator, 'common.search_placeholder') ?>">
      <button class="button button-small" type="submit"><?= quaeriva_t($translator, 'common.search_submit') ?></button>
    </form>
  </div>

  <div class="container community-feed-tabs" role="navigation" aria-label="<?= quaeriva_t($translator, 'topics.filter_all') ?>">
    <?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"' : '' ?>><?= 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">
          <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>
          <a class="button button-secondary" href="<?= quaeriva_escape(quaeriva_url('ask')) ?>"><?= quaeriva_t($translator, 'questions.ask') ?></a>
        </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'] ?? ''));
        $avatar = trim((string) ($item['author_avatar_url'] ?? ''));
        if ($avatar === '' && $author !== '') {
          $avatar = quaeriva_default_avatar_url((int) ($item['author_user_id'] ?? 0));
        }
        $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="cortex-feed-row <?= $isQuestion ? 'is-question' : 'is-discussion' ?>">
          <!-- Metric Rail (Inline-Start) -->
          <div class="cortex-metric-rail">
            <div class="cortex-stat-box stat-votes" title="<?= quaeriva_t($translator, 'common.votes') ?>">
              <strong><?= $votesCount ?></strong>
              <span><?= quaeriva_t($translator, 'common.votes') ?></span>
            </div>
            <?php if ($isQuestion): ?>
              <div class="cortex-stat-box stat-answers <?= $hasBestAnswer ? 'has-best-answer' : ($answersCount > 0 ? 'has-answers' : '') ?>" title="<?= quaeriva_t($translator, 'common.answers') ?>">
                <strong><?= $answersCount ?></strong>
                <span><?= quaeriva_t($translator, 'common.answers') ?></span>
              </div>
            <?php else: ?>
              <div class="cortex-stat-box stat-answers <?= $commentsCount > 0 ? 'has-answers' : '' ?>" title="<?= quaeriva_t($translator, 'topics.comments') ?>">
                <strong><?= $commentsCount ?></strong>
                <span><?= quaeriva_t($translator, 'topics.comments') ?></span>
              </div>
            <?php endif; ?>
            <div class="cortex-stat-box stat-views" title="<?= quaeriva_t($translator, 'common.views') ?>">
              <strong><?= $viewsCount ?></strong>
              <span><?= quaeriva_t($translator, 'common.views') ?></span>
            </div>
          </div>

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

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

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

              <div class="cortex-author-line">
                <?php if ($author !== '' && $username !== ''): ?>
                  <a class="author-inline" href="<?= quaeriva_escape(quaeriva_url('u/' . rawurlencode($username))) ?>">
                    <?php if ($avatar !== ''): ?><img src="<?= quaeriva_escape($avatar) ?>" alt="" width="20" height="20" loading="lazy"><?php endif; ?>
                    <bdi><?= quaeriva_escape($author) ?></bdi>
                  </a>
                <?php elseif ($author !== ''): ?>
                  <span><?= quaeriva_escape($author) ?></span>
                <?php else: ?>
                  <span><?= quaeriva_t($translator, 'common.anonymous') ?></span>
                <?php endif; ?>
                <span aria-hidden="true">·</span>
                <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; ?>
