<?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="container" style="margin-block-start: 1.5rem;">
  <div class="zenith-hero-panel">
    <div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:1.5rem;">
      <div style="max-inline-size: 45rem;">
        <p class="eyebrow" style="color:var(--color-primary); font-weight:800; letter-spacing:0.05em;"><?= quaeriva_t($translator, 'home.eyebrow') ?></p>
        <h1 style="margin:0.25rem 0 0.75rem 0; font-size:2.25rem; font-weight:800;"><?= quaeriva_t($translator, 'home.title') ?></h1>
        <p class="hero-lede" style="margin:0; font-size:1.0625rem; color:var(--color-muted); line-height:1.6;"><?= quaeriva_t($translator, 'home.intro') ?></p>
      </div>
      <div style="display:flex; gap:0.75rem; flex-wrap:wrap;">
        <a class="button" href="<?= quaeriva_escape(quaeriva_url('ask')) ?>" style="box-shadow:0 4px 14px rgba(99,102,241,0.3);"><?= 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>
  </div>
</section>
<?php endif; ?>

<section class="content-section community-home" id="community-feed" style="padding-block-start: 0.5rem;">
  <?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" style="margin-block-end: 1rem;">
    <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') ?>" style="margin-block-end: 1.5rem;">
    <?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'] ?? ''));
        $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="zenith-card <?= $isQuestion ? 'is-question' : 'is-discussion' ?>">
          <!-- Metric Column -->
          <div class="zenith-metric-col">
            <div class="zenith-vote-pill">
              <strong><?= $isQuestion ? $votesCount : $commentsCount ?></strong>
              <span><?= quaeriva_t($translator, $isQuestion ? 'common.votes' : 'topics.comments') ?></span>
            </div>
            <?php if ($isQuestion): ?>
              <span class="zenith-answers-badge <?= $hasBestAnswer ? 'has-best-answer' : ($answersCount > 0 ? 'has-answers' : '') ?>">
                <?= $answersCount ?> <?= quaeriva_t($translator, 'common.answers') ?>
              </span>
            <?php endif; ?>
          </div>

          <!-- Card Body -->
          <div class="zenith-card-body">
            <div class="zenith-card-topline">
              <?php if (trim((string) ($item['category_slug'] ?? '')) !== ''): ?>
                <a class="zenith-badge-category" href="<?= quaeriva_escape(quaeriva_url('c/' . rawurlencode((string) $item['category_slug']))) ?>"><?= quaeriva_escape($item['category_name'] ?? '') ?></a>
              <?php endif; ?>

              <?php if (!$isQuestion && !empty($item['is_pinned'])): ?>
                <span class="badge" style="background-color: var(--color-accent); color: #fff;"><?= quaeriva_t($translator, 'topics.pinned') ?></span>
              <?php endif; ?>

              <?php if ($hasBestAnswer): ?>
                <span class="best-badge"><?= quaeriva_t($translator, 'questions.best_answer') ?></span>
              <?php endif; ?>

              <span style="color: var(--color-muted); margin-inline-start: auto; font-size: 0.8125rem;">
                <time datetime="<?= quaeriva_escape((string) ($item['activity_at'] ?? '')) ?>"><?= quaeriva_escape(quaeriva_relative_time($item['activity_at'] ?? '', $translator)) ?></time>
              </span>
            </div>

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

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

            <div class="zenith-card-footer">
              <div style="display:flex; gap:0.4rem; flex-wrap:wrap; align-items:center;">
                <?php if ($isQuestion && is_array($item['tags'] ?? null) && $item['tags'] !== []): ?>
                  <?php foreach (array_slice($item['tags'], 0, 3) as $tag): ?>
                    <a class="zenith-tag-pill" href="<?= quaeriva_escape(quaeriva_url('t/' . rawurlencode((string) $tag['slug']))) ?>">#<?= quaeriva_escape($tag['name']) ?></a>
                  <?php endforeach; ?>
                <?php endif; ?>
              </div>

              <div style="display:flex; align-items:center; gap:0.5rem; font-size:0.8125rem;">
                <?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="22" height="22" style="border-radius:50%; object-fit:cover;" 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" style="color:var(--color-border);">·</span>
                <span style="color:var(--color-muted);"><bdi><?= $viewsCount ?></bdi> <?= quaeriva_t($translator, 'common.views') ?></span>
              </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; ?>
