<?php
declare(strict_types=1);
$mode = (string) ($mode ?? 'listing');
$topics = is_array($topics ?? null) ? $topics : [];
$topicsMeta = is_array($topicsMeta ?? null) ? $topicsMeta : [];
$categories = is_array($categories ?? null) ? $categories : [];
$languages = is_array($languages ?? null) ? $languages : [];
$filters = is_array($filters ?? null) ? $filters : [];
$values = is_array($values ?? null) ? $values : [];
$postingRules = is_array($postingRules ?? null) ? $postingRules : \App\Community\PostingPolicyService::defaults();
?>
<section class="content-section topics-page">
  <div class="container">
    <?php if ($mode === 'new'): ?>
      <div class="section-heading">
        <div>
          <p class="eyebrow"><?= quaeriva_t($translator, 'topics.eyebrow') ?></p>
          <h1><?= quaeriva_t($translator, 'topics.start') ?></h1>
          <p class="section-lede"><?= quaeriva_t($translator, 'topics.start_intro') ?></p>
        </div>
      </div>
      <?php if (trim((string) ($error ?? '')) !== ''): ?><div class="notice notice-error" role="alert"><?= quaeriva_escape($error) ?></div><?php endif; ?>
      <form class="question-form" method="post" action="<?= quaeriva_escape(quaeriva_url('d/new')) ?>" style="background:var(--color-surface); padding:2rem; border-radius:var(--radius-lg); border:1px solid var(--color-border); box-shadow:var(--shadow-sm);">
        <input type="hidden" name="_csrf" value="<?= quaeriva_escape($csrfToken ?? '') ?>">
        <?= quaeriva_bot_guard_fields() ?>
        <p class="form-hint"><?= quaeriva_t($translator, 'form.required_hint') ?></p>
        <div class="field-group">
          <label for="topic-title"><?= quaeriva_t($translator, 'topics.title_label') ?> <span aria-hidden="true">*</span></label>
          <input id="topic-title" name="title" type="text" dir="auto" value="<?= quaeriva_escape($values['title'] ?? '') ?>" maxlength="255" required>
        </div>
        <div class="field-group">
          <label for="topic-body"><?= quaeriva_t($translator, 'topics.body_label') ?> <span aria-hidden="true">*</span></label>
          <textarea id="topic-body" name="body" dir="auto" rows="10" required <?= quaeriva_rich_editor_attributes($translator, 'full', (string) ($values['body'] ?? '')) ?>><?= quaeriva_escape($values['body'] ?? '') ?></textarea>
        </div>
        <div class="field-group">
          <label for="topic-category"><?= quaeriva_t($translator, 'topics.category_label') ?></label>
          <select id="topic-category" name="category_id">
            <option value="0"><?= quaeriva_t($translator, 'topics.all_categories') ?></option>
            <?php foreach ($categories as $category): ?>
              <option value="<?= (int) ($category['id'] ?? 0) ?>"<?= (int) ($values['category_id'] ?? 0) === (int) ($category['id'] ?? 0) ? ' selected' : '' ?>><?= str_repeat('— ', min(8, max(0, (int) ($category['depth'] ?? 0)))) . quaeriva_escape((string) ($category['name'] ?? '')) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="field-group">
          <label for="topic-locale"><?= quaeriva_t($translator, 'topics.locale_label') ?></label>
          <select id="topic-locale" name="content_locale">
            <?php foreach ($languages as $language): $code = (string) ($language['code'] ?? ''); if ($code === '') continue; ?>
              <option value="<?= quaeriva_escape($code) ?>"<?= (string) ($values['content_locale'] ?? $translator->locale()) === $code ? ' selected' : '' ?>><?= quaeriva_escape((string) ($language['native_name'] ?? $language['name'] ?? $code)) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="field-group">
          <label for="topic-kind"><?= quaeriva_t($translator, 'topics.kind_label') ?></label>
          <select id="topic-kind" name="kind">
            <option value="discussion"<?= ($values['kind'] ?? 'discussion') === 'discussion' ? ' selected' : '' ?>><?= quaeriva_t($translator, 'topics.discussion') ?></option>
            <?php if (quaeriva_user_has_role($currentUser ?? null, 'admin', 'moderator')): ?>
              <option value="announcement"<?= ($values['kind'] ?? '') === 'announcement' ? ' selected' : '' ?>><?= quaeriva_t($translator, 'topics.announcement') ?></option>
            <?php endif; ?>
          </select>
        </div>
        <button class="button" type="submit"><?= quaeriva_t($translator, 'topics.create') ?></button>
      </form>
    <?php else: ?>
      <?php if (max(0, (int) ($_GET['submitted'] ?? 0)) > 0): ?><div class="notice" role="status"><?= quaeriva_t($translator, 'topics.submission_received') ?></div><?php endif; ?>
      <?php $topicTotal = max(0, (int) ($topicsMeta['total'] ?? count($topics))); ?>

      <div class="rawy-topic-hero-banner">
        <div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:1rem;">
          <div>
            <p class="eyebrow" style="color:var(--color-primary); font-weight:700;"><?= quaeriva_t($translator, 'topics.eyebrow') ?></p>
            <h1 style="margin:0.25rem 0 0.5rem 0;"><?= quaeriva_t($translator, 'topics.title') ?></h1>
            <p class="section-lede" style="margin:0;"><?= quaeriva_t($translator, 'topics.intro') ?></p>
          </div>
          <a class="button" href="<?= quaeriva_escape(quaeriva_url('d/new')) ?>"><?= quaeriva_t($translator, 'topics.start') ?></a>
        </div>
      </div>

      <nav class="topics-tabs" aria-label="<?= quaeriva_t($translator, 'topics.nav') ?>" style="margin-block-end: 1rem;">
        <a class="topics-tab" href="<?= quaeriva_escape(quaeriva_url()) ?>#latest-questions"><?= quaeriva_t($translator, 'topics.filter_all') ?></a>
        <a class="topics-tab" href="<?= quaeriva_escape(quaeriva_url() . '#latest-questions') ?>"><?= quaeriva_t($translator, 'topics.filter_questions') ?></a>
        <a class="topics-tab is-active" aria-current="page" href="<?= quaeriva_escape(quaeriva_url('d')) ?>"><?= quaeriva_t($translator, 'topics.filter_topics') ?></a>
      </nav>

      <form class="topics-filter-panel" method="get" action="<?= quaeriva_escape(quaeriva_url('d')) ?>" style="background:var(--color-surface); border:1px solid var(--color-border); border-radius:var(--radius-lg); padding:1.25rem; margin-block-end:1.5rem;">
        <div class="topics-filter-search">
          <label for="topics-search"><?= quaeriva_t($translator, 'topics.search') ?></label>
          <input id="topics-search" type="search" name="search" value="<?= quaeriva_escape($filters['search'] ?? '') ?>" placeholder="<?= quaeriva_t($translator, 'topics.search_placeholder') ?>">
        </div>
        <div class="topics-filter-grid">
          <label for="topics-category"><?= quaeriva_t($translator, 'topics.filter_category') ?>
            <select id="topics-category" name="category">
              <option value=""><?= quaeriva_t($translator, 'topics.all_categories') ?></option>
              <?php foreach ($categories as $category): ?>
                <option value="<?= quaeriva_escape((string) ($category['slug'] ?? $category['id'] ?? '')) ?>"<?= ((string) ($filters['category'] ?? '') !== '' && (string) ($filters['category'] ?? '') === (string) ($category['slug'] ?? $category['id'] ?? '')) || ((int) ($filters['category_id'] ?? 0) > 0 && (int) ($filters['category_id'] ?? 0) === (int) ($category['id'] ?? 0)) ? ' selected' : '' ?>><?= str_repeat('— ', min(8, max(0, (int) ($category['depth'] ?? 0)))) . quaeriva_escape((string) ($category['name'] ?? '')) ?></option>
              <?php endforeach; ?>
            </select>
          </label>
          <label for="topics-locale"><?= quaeriva_t($translator, 'topics.filter_locale') ?>
            <select id="topics-locale" name="locale">
              <option value=""><?= quaeriva_t($translator, 'topics.all_locales') ?></option>
              <?php foreach ($languages as $language): $code = (string) ($language['code'] ?? ''); if ($code === '') continue; ?>
                <option value="<?= quaeriva_escape($code) ?>"<?= (string) ($filters['locale'] ?? '') === $code ? ' selected' : '' ?>><?= quaeriva_escape((string) ($language['native_name'] ?? $language['name'] ?? $code)) ?></option>
              <?php endforeach; ?>
            </select>
          </label>
          <label for="topics-kind"><?= quaeriva_t($translator, 'topics.filter_kind') ?>
            <select id="topics-kind" name="kind">
              <option value=""><?= quaeriva_t($translator, 'topics.all_kinds') ?></option>
              <option value="discussion"<?= ($filters['kind'] ?? '') === 'discussion' ? ' selected' : '' ?>><?= quaeriva_t($translator, 'topics.discussion') ?></option>
              <option value="announcement"<?= ($filters['kind'] ?? '') === 'announcement' ? ' selected' : '' ?>><?= quaeriva_t($translator, 'topics.announcement') ?></option>
            </select>
          </label>
        </div>
        <button class="button button-secondary topics-filter-submit" type="submit"><?= quaeriva_t($translator, 'common.search_submit') ?></button>
      </form>

      <?php if ($topics === []): ?>
        <div class="empty-state">
          <h2><?= quaeriva_t($translator, 'topics.no_topics') ?></h2>
          <p><?= quaeriva_t($translator, 'topics.no_topics_hint') ?></p>
          <a class="button button-secondary" href="<?= quaeriva_escape(quaeriva_url('d/new')) ?>"><?= quaeriva_t($translator, 'topics.start') ?></a>
        </div>
      <?php else: ?>
        <div style="display:flex; flex-direction:column; gap:1.25rem;">
          <?php foreach ($topics as $topic):
            $topicSlug = trim((string) ($topic['slug'] ?? ''));
            if ($topicSlug === '') continue;
            $excerpt = trim(strip_tags(quaeriva_rich_text((string) ($topic['body'] ?? ''), 'comment')));
            $excerpt = function_exists('mb_substr') ? mb_substr($excerpt, 0, 220, 'UTF-8') : substr($excerpt, 0, 220);
            $author = trim((string) ($topic['author_name'] ?? ''));
          ?>
            <article class="rawy-feed-card is-discussion">
              <div class="rawy-card-main">
                <div class="rawy-card-header">
                  <?php if ((int) ($topic['is_pinned'] ?? 0) === 1): ?>
                    <span class="badge" style="background-color: var(--color-accent); color: #fff;"><?= quaeriva_t($translator, 'topics.pinned') ?></span>
                  <?php endif; ?>
                  <?php if (($topic['kind'] ?? '') === 'announcement'): ?>
                    <span class="badge" style="background-color: var(--color-secondary); color: #fff;"><?= quaeriva_t($translator, 'topics.announcement_badge') ?></span>
                  <?php endif; ?>
                  <?php if ((int) ($topic['is_locked'] ?? 0) === 1): ?>
                    <span class="badge" style="background-color: var(--color-muted); color: #fff;"><?= quaeriva_t($translator, 'topics.locked') ?></span>
                  <?php endif; ?>
                  <?php if (trim((string) ($topic['category_name'] ?? '')) !== ''): ?>
                    <span class="rawy-category-badge"><?= quaeriva_escape((string) $topic['category_name']) ?></span>
                  <?php endif; ?>
                  <span style="color: var(--color-muted); margin-inline-start: auto; font-size:0.8125rem;">
                    <time datetime="<?= quaeriva_escape((string) ($topic['last_activity_at'] ?? $topic['updated_at'] ?? '')) ?>"><?= quaeriva_escape(quaeriva_relative_time($topic['last_activity_at'] ?? $topic['updated_at'] ?? null, $translator)) ?></time>
                  </span>
                </div>

                <h3 class="rawy-card-title">
                  <a dir="auto" href="<?= quaeriva_escape(quaeriva_topic_url($topicSlug)) ?>"><?= quaeriva_escape($topic['title'] ?? '') ?></a>
                </h3>

                <p class="rawy-card-excerpt" dir="auto"><?= quaeriva_escape($excerpt) ?></p>

                <div class="rawy-card-footer">
                  <div class="rawy-meta-group">
                    <span style="font-weight:600;"><bdi><?= quaeriva_escape($author !== '' ? $author : $translator->get('common.anonymous')) ?></bdi></span>
                  </div>
                  <div class="rawy-meta-group">
                    <span class="rawy-stat-pill"><strong><?= (int) ($topic['comments_count'] ?? 0) ?></strong> <?= quaeriva_t($translator, 'topics.comments') ?></span>
                    <span class="rawy-stat-pill"><strong><?= (int) ($topic['views_count'] ?? 0) ?></strong> <?= quaeriva_t($translator, 'common.views') ?></span>
                  </div>
                </div>
              </div>
            </article>
          <?php endforeach; ?>
        </div>

        <?php $page = max(1, (int) ($topicsMeta['page'] ?? 1)); $pages = max(1, (int) ($topicsMeta['total_pages'] ?? 1)); if ($pages > 1): ?>
          <nav class="pagination" aria-label="<?= quaeriva_t($translator, 'topics.pagination') ?>" style="margin-block-start: 1.5rem;">
            <span><?= quaeriva_t($translator, 'topics.page_summary', ['page' => $page, 'pages' => $pages]) ?></span>
            <?php if ($page > 1): ?><a class="button button-small button-secondary" href="<?= quaeriva_escape(quaeriva_url('d', array_merge($filters, ['page' => $page - 1]))) ?>"><?= quaeriva_t($translator, 'topics.previous_page') ?></a><?php endif; ?>
            <?php if ($page < $pages): ?><a class="button button-small button-secondary" href="<?= quaeriva_escape(quaeriva_url('d', array_merge($filters, ['page' => $page + 1]))) ?>"><?= quaeriva_t($translator, 'topics.next_page') ?></a><?php endif; ?>
          </nav>
        <?php endif; ?>
      <?php endif; ?>
    <?php endif; ?>
  </div>
</section>
