<?php
declare(strict_types=1);
$taxonomy = is_array($taxonomy ?? null) ? $taxonomy : [];
$type = (string) ($type ?? 'category');
$isCategory = ($type === 'category');
$questionsList = is_array($questions ?? null) ? $questions : [];
$topicsData = is_array($topics ?? null) ? $topics : ['items' => [], 'total' => 0, 'page' => 1, 'per_page' => 20, 'total_pages' => 1];
$topicItems = is_array($topicsData['items'] ?? null) ? $topicsData['items'] : [];
$title = (string) ($taxonomy['name'] ?? '');
$description = (string) ($taxonomy['description'] ?? '');
$questionCount = count($questionsList);
$topicCount = max(0, (int) ($topicsData['total'] ?? count($topicItems)));
$taxonomyPath = ($type === 'tag' ? 't/' : 'c/') . rawurlencode((string) ($taxonomy['slug'] ?? ''));
$isFollowing = (bool) ($isFollowing ?? false);
$rawTab = (string) ($_GET['tab'] ?? 'all');
$activeTab = in_array($rawTab, ['all', 'questions', 'discussions'], true) ? $rawTab : 'all';
?>
<section class="content-section" style="padding-block: 2.5rem 4rem;">
  <div class="container" style="max-inline-size: 52rem;">
    <div style="margin-block-end: 1.5rem; border-block-end: 1px solid #EAE3D5; padding-block-end: 1.25rem; display:flex; justify-content:space-between; align-items:flex-start; flex-wrap:wrap; gap:1rem;">
      <div>
        <p class="eyebrow" style="color:#842339; font-weight:700;"><?= quaeriva_t($translator, $isCategory ? 'taxonomy.category' : 'taxonomy.tag') ?></p>
        <h1 style="margin:0 0 0.5rem 0; font-size:2rem; font-weight:800; color:#1F1D1A;"><?= quaeriva_escape($title) ?></h1>
        <?php if ($description !== ''): ?>
          <p style="color:#635B52; margin:0; line-height:1.7;"><?= quaeriva_escape($description) ?></p>
        <?php endif; ?>
      </div>
      <?php if (($site['follows_enabled'] ?? true) === true): ?>
        <div class="taxonomy-follow">
          <?php if (($currentUser ?? null) !== null): ?>
            <form method="post" action="<?= quaeriva_escape(quaeriva_url(($type === 'tag' ? 't/' : 'c/') . rawurlencode((string) ($taxonomy['slug'] ?? '')) . '/follow')) ?>">
              <input type="hidden" name="_csrf" value="<?= quaeriva_escape($csrfToken ?? '') ?>">
              <button class="button button-secondary button-small" type="submit"><?= quaeriva_t($translator, $isFollowing ? 'taxonomy.unfollow' : 'taxonomy.follow') ?></button>
            </form>
          <?php else: ?>
            <a class="button button-secondary button-small" href="<?= quaeriva_escape(quaeriva_url('login', ['redirect' => $currentPath ?? quaeriva_url()])) ?>"><?= quaeriva_t($translator, 'taxonomy.login_to_follow') ?></a>
          <?php endif; ?>
        </div>
      <?php endif; ?>
    </div>

    <!-- Category Tabs Navigation -->
    <?php if ($isCategory && ($questionCount > 0 || $topicCount > 0)): ?>
      <nav class="community-feed-tabs" aria-label="<?= quaeriva_t($translator, 'taxonomy.category') ?>" style="margin-block-end: 1.5rem; display: flex; gap: 0.5rem;">
        <a class="button button-small <?= $activeTab === 'all' ? '' : 'button-secondary' ?>" href="<?= quaeriva_escape(quaeriva_url($taxonomyPath)) ?>"<?= $activeTab === 'all' ? ' aria-current="page"' : '' ?>><?= quaeriva_t($translator, 'topics.filter_all') ?> (<bdi><?= $questionCount + $topicCount ?></bdi>)</a>
        <a class="button button-small <?= $activeTab === 'questions' ? '' : 'button-secondary' ?>" href="<?= quaeriva_escape(quaeriva_url($taxonomyPath, ['tab' => 'questions'])) ?>"<?= $activeTab === 'questions' ? ' aria-current="page"' : '' ?>><?= quaeriva_t($translator, 'topics.filter_questions') ?> (<bdi><?= $questionCount ?></bdi>)</a>
        <a class="button button-small <?= $activeTab === 'discussions' ? '' : 'button-secondary' ?>" href="<?= quaeriva_escape(quaeriva_url($taxonomyPath, ['tab' => 'discussions'])) ?>"<?= $activeTab === 'discussions' ? ' aria-current="page"' : '' ?>><?= quaeriva_t($translator, 'topics.filter_topics') ?> (<bdi><?= $topicCount ?></bdi>)</a>
      </nav>
    <?php endif; ?>

    <?php if ($questionsList === [] && $topicItems === []): ?>
      <div class="empty-state"><h2><?= quaeriva_t($translator, 'taxonomy.empty') ?></h2><p><?= quaeriva_t($translator, 'taxonomy.empty_hint') ?></p></div>
    <?php else: ?>
      <?php if (($activeTab === 'all' || $activeTab === 'questions') && $questionsList !== []): ?>
        <?php if ($activeTab === 'all' && $topicItems !== []): ?>
          <div class="section-heading" style="margin-block-end: 0.75rem;"><h2><?= quaeriva_t($translator, 'taxonomy.questions_heading', ['count' => $questionCount]) ?></h2></div>
        <?php endif; ?>
        <div class="community-feed" style="margin-block-end: 2rem;">
          <?php foreach ($questionsList as $item):
            $itemUrl = quaeriva_question_url((string) ($item['slug'] ?? ''), (int) ($item['id'] ?? 0));
            $bodyText = strip_tags((string) ($item['body'] ?? ''));
            $wordCount = max(1, count(preg_split('/\s+/u', $bodyText, -1, PREG_SPLIT_NO_EMPTY) ?: []));
            $readingMinutes = max(1, (int) ceil($wordCount / 180));
            $answersCount = (int) ($item['answers_count'] ?? 0);
          ?>
            <article class="hikaya-story-card">
              <h2 class="hikaya-story-title"><a dir="auto" href="<?= quaeriva_escape($itemUrl) ?>"><?= quaeriva_escape((string) ($item['title'] ?? '')) ?></a></h2>
              <p class="hikaya-story-excerpt" dir="auto"><?= quaeriva_escape(mb_strimwidth($bodyText, 0, 220, '…', 'UTF-8')) ?></p>
              <div class="hikaya-story-meta">
                <span class="badge"><?= quaeriva_t($translator, 'common.questions') ?></span>
                <span class="hikaya-reading-time">⏱ <?= $readingMinutes ?> <?= quaeriva_t($translator, 'common.minutes') ?></span>
                <span><?= quaeriva_escape($item['author_name'] ?? $translator->get('common.anonymous')) ?></span>
                <span>·</span>
                <span><?= $answersCount ?> <?= quaeriva_t($translator, 'common.answers') ?></span>
              </div>
            </article>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>

      <?php if ($isCategory && ($activeTab === 'all' || $activeTab === 'discussions') && $topicItems !== []): ?>
        <?php if ($activeTab === 'all' && $questionsList !== []): ?>
          <div class="section-heading" style="margin-block-end: 0.75rem;"><h2><?= quaeriva_t($translator, 'taxonomy.discussions_heading', ['count' => $topicCount]) ?></h2></div>
        <?php endif; ?>
        <div class="community-feed">
          <?php foreach ($topicItems as $topic):
            $topicSlug = trim((string) ($topic['slug'] ?? ''));
            if ($topicSlug === '') continue;
            $topicUrl = quaeriva_url('d/' . rawurlencode($topicSlug));
            $bodyText = strip_tags((string) ($topic['body'] ?? ''));
            $wordCount = max(1, count(preg_split('/\s+/u', $bodyText, -1, PREG_SPLIT_NO_EMPTY) ?: []));
            $readingMinutes = max(1, (int) ceil($wordCount / 180));
            $commentsCount = (int) ($topic['comments_count'] ?? 0);
          ?>
            <article class="hikaya-story-card">
              <h2 class="hikaya-story-title"><a dir="auto" href="<?= quaeriva_escape($topicUrl) ?>"><?= quaeriva_escape((string) ($topic['title'] ?? '')) ?></a></h2>
              <p class="hikaya-story-excerpt" dir="auto"><?= quaeriva_escape(mb_strimwidth($bodyText, 0, 220, '…', 'UTF-8')) ?></p>
              <div class="hikaya-story-meta">
                <span class="badge badge-secondary"><?= quaeriva_t($translator, 'topics.discussion') ?></span>
                <span class="hikaya-reading-time">⏱ <?= $readingMinutes ?> <?= quaeriva_t($translator, 'common.minutes') ?></span>
                <span><?= quaeriva_escape($topic['author_name'] ?? $translator->get('common.anonymous')) ?></span>
                <span>·</span>
                <span><?= $commentsCount ?> <?= quaeriva_t($translator, 'topics.comments') ?></span>
              </div>
            </article>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    <?php endif; ?>
  </div>
</section>
