<?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 taxonomy-section">
  <div class="container taxonomy-container">
    <div style="background:linear-gradient(135deg, rgba(79, 70, 229, 0.08), rgba(14, 165, 233, 0.08)); border:1px solid var(--color-border); border-radius:var(--radius-lg); padding:1.5rem; margin-block-end:1.5rem; display:flex; justify-content:space-between; align-items:flex-start; flex-wrap:wrap; gap:1rem;">
      <div>
        <p class="eyebrow" style="color:var(--color-primary); font-weight:700;"><?= quaeriva_t($translator, $isCategory ? 'taxonomy.category' : 'taxonomy.tag') ?></p>
        <h1 style="margin:0.25rem 0 0.5rem 0; font-size:2rem; font-weight:800;"><?= quaeriva_escape($title) ?></h1>
        <?php if ($description !== ''): ?>
          <p style="color:var(--color-muted); margin:0; line-height:1.6;"><?= 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):
            $votesCount = (int) ($item['votes_count'] ?? 0);
            $answersCount = (int) ($item['answers_count'] ?? 0);
            $itemUrl = quaeriva_question_url((string) ($item['slug'] ?? ''), (int) ($item['id'] ?? 0));
          ?>
            <article class="zenith-card">
              <div class="zenith-card-header">
                <span class="badge"><?= quaeriva_t($translator, 'common.questions') ?></span>
                <span style="font-size:0.75rem; color:var(--color-muted);"><?= quaeriva_escape($item['author_name'] ?? $translator->get('common.anonymous')) ?></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, 180, '…', 'UTF-8')) ?></p>
              <div class="zenith-card-footer">
                <span class="badge badge-subtle">▲ <?= $votesCount ?> <?= quaeriva_t($translator, 'common.votes') ?></span>
                <span class="badge badge-subtle">💬 <?= $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));
            $commentsCount = (int) ($topic['comments_count'] ?? 0);
          ?>
            <article class="zenith-card">
              <div class="zenith-card-header">
                <span class="badge badge-secondary"><?= quaeriva_t($translator, 'topics.discussion') ?></span>
                <span style="font-size:0.75rem; color:var(--color-muted);"><?= quaeriva_escape($topic['author_name'] ?? $translator->get('common.anonymous')) ?></span>
              </div>
              <h3 class="zenith-card-title"><a dir="auto" href="<?= quaeriva_escape($topicUrl) ?>"><?= quaeriva_escape((string) ($topic['title'] ?? '')) ?></a></h3>
              <p class="zenith-card-excerpt" dir="auto"><?= quaeriva_escape(mb_strimwidth(strip_tags((string) ($topic['body'] ?? '')), 0, 180, '…', 'UTF-8')) ?></p>
              <div class="zenith-card-footer">
                <span class="badge badge-subtle">💬 <?= $commentsCount ?> <?= quaeriva_t($translator, 'topics.comments') ?></span>
              </div>
            </article>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    <?php endif; ?>
  </div>
</section>
