<?php
declare(strict_types=1);
// The home view receives the unified feed, not separate question/topic lists.
$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') : '';
$feedAvailable = (bool) ($dbAvailable ?? true);
?>
<?php if ($isGuest): ?>
<section class="content-section hikaya-hero">
  <div class="container hikaya-hero-inner">
    <p class="eyebrow"><?= quaeriva_t($translator, 'home.eyebrow') ?></p>
    <h1><?= quaeriva_t($translator, 'home.title') ?></h1>
    <p class="hikaya-hero-lede"><?= quaeriva_t($translator, 'home.intro') ?></p>
  </div>
</section>
<?php endif; ?>

<section class="content-section hikaya-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 hikaya-toolbar">
    <h2 class="hikaya-toolbar-title"><?= quaeriva_t($translator, 'questions.latest') ?></h2>
    <div class="hikaya-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>

  <div class="container">
    <nav class="hikaya-feed-tabs" aria-label="<?= quaeriva_t($translator, 'questions.latest') ?>">
      <?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])) ?>#community-feed"<?= $activeFilter === $key ? ' aria-current="page"' : '' ?>><?= quaeriva_t($translator, $label) ?></a>
      <?php endforeach; ?>
    </nav>
  </div>

  <div class="container hikaya-grid<?= $homeSidebar !== '' ? ' has-hikaya-sidebar' : '' ?>">
    <div class="hikaya-feed">
      <?php if (!$feedAvailable): ?>
        <div class="empty-state"><p><?= quaeriva_t($translator, 'common.database_unavailable') ?></p></div>
      <?php elseif ($items === []): ?>
        <div class="empty-state">
          <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 else: ?>
        <?php foreach ($items as $item):
          $isQuestion = (string) ($item['type'] ?? 'question') === 'question';
          $slug = (string) ($item['slug'] ?? '');
          $itemUrl = $isQuestion
            ? quaeriva_question_url($slug, (int) ($item['id'] ?? 0))
            : quaeriva_url('d/' . rawurlencode($slug));
          // body is Markdown source, so it is excerpted as text and never rendered as HTML.
          $bodyText = trim(strip_tags((string) ($item['body'] ?? '')));
          $words = preg_split('/\s+/u', $bodyText, -1, PREG_SPLIT_NO_EMPTY) ?: [];
          $readingMinutes = max(1, (int) ceil(count($words) / 180));
          $authorName = trim((string) ($item['author_name'] ?? ''));
          $authorUsername = trim((string) ($item['author_username'] ?? ''));
          $replies = $isQuestion ? (int) ($item['answers_count'] ?? 0) : (int) ($item['comments_count'] ?? 0);
          $activityAt = (string) ($item['activity_at'] ?? $item['created_at'] ?? '');
        ?>
          <article class="hikaya-story-card<?= $isQuestion ? '' : ' is-discussion' ?>">
            <div class="hikaya-story-kicker">
              <span class="hikaya-type"><?= $isQuestion ? quaeriva_t($translator, 'topics.filter_questions') : quaeriva_t($translator, 'topics.discussion') ?></span>
              <?php if (!$isQuestion && !empty($item['is_pinned'])): ?><span class="badge"><?= quaeriva_t($translator, 'topics.pinned') ?></span><?php endif; ?>
              <?php if ($isQuestion && !empty($item['best_answer_id'])): ?><span class="best-badge"><?= quaeriva_t($translator, 'questions.best_answer') ?></span><?php endif; ?>
            </div>
            <h2 class="hikaya-story-title"><a dir="auto" href="<?= quaeriva_escape($itemUrl) ?>"><?= quaeriva_escape((string) ($item['title'] ?? '')) ?></a></h2>
            <?php if ($bodyText !== ''): ?>
              <p class="hikaya-story-excerpt" dir="auto"><?= quaeriva_escape(mb_strimwidth($bodyText, 0, 220, '…', 'UTF-8')) ?></p>
            <?php endif; ?>
            <div class="hikaya-story-meta">
              <span class="hikaya-reading-time">⏱ <?= (int) $readingMinutes ?> <?= quaeriva_t($translator, 'common.reading_minutes') ?></span>
              <span>·</span>
              <?php if ($authorUsername !== ''): ?>
                <a href="<?= quaeriva_escape(quaeriva_url('u/' . rawurlencode($authorUsername))) ?>"><?= quaeriva_escape($authorName !== '' ? $authorName : $authorUsername) ?></a>
              <?php else: ?>
                <span><?= quaeriva_t($translator, 'common.anonymous') ?></span>
              <?php endif; ?>
              <span>·</span>
              <time datetime="<?= quaeriva_escape($activityAt) ?>"><?= quaeriva_escape(quaeriva_relative_time($activityAt, $translator)) ?></time>
              <span>·</span>
              <span><?= (int) $replies ?> <?= $isQuestion ? quaeriva_t($translator, 'common.answers') : quaeriva_t($translator, 'topics.comments') ?></span>
            </div>
            <?php if (!empty($item['tags']) && is_array($item['tags'])): ?>
              <div class="hikaya-tags">
                <?php foreach (array_slice($item['tags'], 0, 4) as $tag): ?>
                  <a href="<?= quaeriva_escape(quaeriva_url('t/' . rawurlencode((string) ($tag['slug'] ?? '')))) ?>"><?= quaeriva_escape((string) ($tag['name'] ?? '')) ?></a>
                <?php endforeach; ?>
              </div>
            <?php endif; ?>
          </article>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>

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

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