<?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" 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="rawy-feed-card <?= $isQuestion ? 'is-question' : 'is-discussion' ?>">
          <!-- Avatar First Column -->
          <div class="rawy-avatar-col">
            <?php if ($author !== '' && $username !== ''): ?>
              <a href="<?= quaeriva_escape(quaeriva_url('u/' . rawurlencode($username))) ?>" title="<?= quaeriva_escape($author) ?>">
                <?php if ($avatar !== ''): ?>
                  <img class="rawy-author-avatar" src="<?= quaeriva_escape($avatar) ?>" alt="<?= quaeriva_escape($author) ?>" width="48" height="48" loading="lazy">
                <?php else: ?>
                  <span class="rawy-author-avatar" style="display:flex;align-items:center;justify-content:center;background:var(--color-surface-soft);font-weight:700;"><?= quaeriva_escape(mb_substr($author, 0, 1, 'UTF-8')) ?></span>
                <?php endif; ?>
              </a>
            <?php else: ?>
              <span class="rawy-author-avatar" style="display:flex;align-items:center;justify-content:center;background:var(--color-surface-soft);font-weight:700;color:var(--color-muted);">?</span>
            <?php endif; ?>
          </div>

          <!-- Main Card Column -->
          <div class="rawy-card-main">
            <div class="rawy-card-header">
              <?php if (trim((string) ($item['category_slug'] ?? '')) !== ''): ?>
                <a class="rawy-category-badge" 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;">
                <time datetime="<?= quaeriva_escape((string) ($item['activity_at'] ?? '')) ?>"><?= quaeriva_escape(quaeriva_relative_time($item['activity_at'] ?? '', $translator)) ?></time>
              </span>
            </div>

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

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

            <div class="rawy-card-footer">
              <div class="rawy-meta-group">
                <span style="font-weight: 600; color: var(--color-text);">
                  <?php if ($author !== '' && $username !== ''): ?>
                    <a class="author-inline" href="<?= quaeriva_escape(quaeriva_url('u/' . rawurlencode($username))) ?>"><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>

                <?php if ($isQuestion && is_array($item['tags'] ?? null) && $item['tags'] !== []): ?>
                  <span aria-hidden="true" style="color: var(--color-border);">|</span>
                  <div style="display:flex; gap:0.35rem; flex-wrap:wrap;">
                    <?php foreach (array_slice($item['tags'], 0, 3) as $tag): ?>
                      <a href="<?= quaeriva_escape(quaeriva_url('t/' . rawurlencode((string) $tag['slug']))) ?>" style="color: var(--color-muted); text-decoration: none; font-size: 0.8125rem;">#<?= quaeriva_escape($tag['name']) ?></a>
                    <?php endforeach; ?>
                  </div>
                <?php endif; ?>
              </div>

              <div class="rawy-meta-group">
                <?php if ($isQuestion): ?>
                  <span class="rawy-stat-pill"><strong><?= $answersCount ?></strong> <?= quaeriva_t($translator, 'common.answers') ?></span>
                  <span class="rawy-stat-pill"><strong><?= $votesCount ?></strong> <?= quaeriva_t($translator, 'common.votes') ?></span>
                <?php else: ?>
                  <span class="rawy-stat-pill"><strong><?= $commentsCount ?></strong> <?= quaeriva_t($translator, 'topics.comments') ?></span>
                <?php endif; ?>
                <span class="rawy-stat-pill"><strong><?= $viewsCount ?></strong> <?= 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; ?>
