<?php
declare(strict_types=1);
$contentDirection = $topic !== null ? $localeContext->contentDirection($topic['content_locale'] ?? null) : $localeContext->htmlAttributes()['dir'];
$postingRules = is_array($postingRules ?? null) ? array_replace(\App\Community\PostingPolicyService::defaults(), $postingRules) : \App\Community\PostingPolicyService::defaults();
$topicCommentMin = max(0, (int) ($postingRules['topic_comment_min'] ?? 3));
$topicCommentMax = max(0, (int) ($postingRules['topic_comment_max'] ?? 600));
$topicSlug = (string) ($topic['slug'] ?? '');
$topicUrl = quaeriva_url('d/' . rawurlencode($topicSlug));
$authorUsername = trim((string) ($topic['author_username'] ?? ''));
$isReported = in_array((int) ($topic['id'] ?? 0), (array) ($reportedItems['topic'] ?? []), true);
$reportReasons = ['spam', 'abuse', 'duplicate', 'misleading', 'other'];
?>
<section class="content-section topic-detail-section">
  <div class="container topic-container" style="max-inline-size: 54rem;">
    <?php if (trim((string) ($notice ?? '')) !== ''): ?><div class="notice" role="status"><?= quaeriva_escape($notice) ?></div><?php endif; ?>
    <?php if ((string) ($_GET['commented'] ?? '') === 'pending'): ?><div class="notice" role="status"><?= quaeriva_t($translator, 'topics.comment_pending') ?></div><?php endif; ?>

    <article class="orbit-detail-wrap">
      <div class="orbit-detail-body">
        <div class="orbit-post-meta" style="margin-block-end:0.75rem;">
          <?php if (trim((string) ($topic['category_slug'] ?? '')) !== ''): ?>
            <a class="orbit-sub-badge" href="<?= quaeriva_escape(quaeriva_url('c/' . rawurlencode((string) $topic['category_slug']))) ?>">c/<?= quaeriva_escape($topic['category_name'] ?? '') ?></a>
            <span aria-hidden="true">•</span>
          <?php endif; ?>
          <span>u/<?= quaeriva_escape($authorUsername ?: $translator->get('common.anonymous')) ?></span>
          <span aria-hidden="true">•</span>
          <time datetime="<?= quaeriva_escape((string) ($topic['created_at'] ?? '')) ?>"><?= quaeriva_escape(quaeriva_relative_time($topic['created_at'] ?? '', $translator)) ?></time>
        </div>

        <h1 dir="<?= quaeriva_escape($contentDirection) ?>" style="margin:0 0 1rem 0; font-size:1.75rem; line-height:1.3;"><?= quaeriva_escape($topic['title'] ?? '') ?></h1>

        <div class="rich-text" dir="<?= quaeriva_escape($contentDirection) ?>" style="font-size:1rem; line-height:1.65;">
          <?= quaeriva_rich_text($topic['body'] ?? '', 'full') ?>
        </div>

        <div class="orbit-action-bar" style="margin-block-start:1.25rem; padding-block-start:0.75rem; border-block-start:1px solid var(--color-border);">
          <?php if (($site['follows_enabled'] ?? true) === true && $currentUser !== null): ?>
            <form method="post" action="<?= quaeriva_escape(quaeriva_url('d/' . rawurlencode($topicSlug) . '/follow')) ?>">
              <input type="hidden" name="_csrf" value="<?= quaeriva_escape($csrfToken) ?>">
              <button class="orbit-pill-btn" type="submit">🔖 <?= quaeriva_t($translator, !empty($isFollowing) ? 'topics.unfollow' : 'topics.follow') ?></button>
            </form>
          <?php endif; ?>
          <?php if ($currentUser !== null && !$isReported): ?>
            <details class="report-action" style="margin-inline-start:auto;">
              <summary class="orbit-pill-btn">🚩 <?= quaeriva_t($translator, 'topics.report') ?></summary>
              <form class="compact-form report-popover" method="post" action="<?= quaeriva_escape(quaeriva_url('d/' . rawurlencode($topicSlug) . '/report')) ?>">
                <input type="hidden" name="_csrf" value="<?= quaeriva_escape($csrfToken) ?>">
                <select name="reason"><?php foreach ($reportReasons as $reason): ?><option value="<?= quaeriva_escape($reason) ?>"><?= quaeriva_t($translator, 'questions.report_reasons.' . $reason) ?></option><?php endforeach; ?></select>
                <textarea name="notes" rows="2" maxlength="1000" dir="<?= quaeriva_escape($contentDirection) ?>"></textarea>
                <button class="button button-small" type="submit"><?= quaeriva_t($translator, 'questions.report_submit') ?></button>
              </form>
            </details>
          <?php endif; ?>
        </div>
      </div>
    </article>

    <!-- Comments -->
    <section class="topic-comments-section" style="margin-block-start:1.5rem;">
      <h2 style="font-size:1.25rem; font-weight:700; margin-block-end:1rem;"><?= quaeriva_t($translator, 'topics.comments_heading', ['count' => count($comments ?? [])]) ?></h2>

      <?php if (($comments ?? []) !== []): ?>
        <div style="background:var(--color-surface); border:1px solid var(--color-border); border-radius:var(--radius-sm); padding:1rem; margin-block-end:1.5rem;">
          <?php foreach ($comments as $comment):
            $commentId = (int) ($comment['id'] ?? 0);
            $cUsername = trim((string) ($comment['author_username'] ?? ''));
          ?>
            <div id="comment-<?= $commentId ?>" class="orbit-thread-comment">
              <div style="font-size:0.75rem; color:var(--color-muted); margin-block-end:0.25rem;">
                <strong>u/<?= quaeriva_escape($cUsername ?: $translator->get('common.anonymous')) ?></strong>
                <span aria-hidden="true">•</span>
                <time datetime="<?= quaeriva_escape((string) ($comment['created_at'] ?? '')) ?>"><?= quaeriva_escape(quaeriva_relative_time($comment['created_at'] ?? '', $translator)) ?></time>
              </div>
              <div class="rich-text" dir="<?= quaeriva_escape($contentDirection) ?>" style="font-size:0.875rem;">
                <?= quaeriva_rich_text($comment['body'] ?? '', 'comment') ?>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>

      <?php if ($currentUser !== null): ?>
        <div style="background:var(--color-surface); border:1px solid var(--color-border); border-radius:var(--radius-sm); padding:1.25rem;">
          <h3 style="font-size:1rem; margin:0 0 0.75rem 0;"><?= quaeriva_t($translator, 'topics.add_comment') ?></h3>
          <form method="post" action="<?= quaeriva_escape(quaeriva_url('d/' . rawurlencode($topicSlug) . '/comments')) ?>">
            <input type="hidden" name="_csrf" value="<?= quaeriva_escape($csrfToken) ?>">
            <?= quaeriva_bot_guard_fields() ?>
            <textarea name="body" class="comment-textarea" dir="<?= quaeriva_escape($contentDirection) ?>" rows="3"<?= quaeriva_rich_editor_attributes($translator, 'comment', '') ?><?= $topicCommentMax > 0 ? ' maxlength="' . $topicCommentMax . '"' : '' ?><?= $topicCommentMin > 0 ? ' minlength="' . $topicCommentMin . '"' : '' ?> required placeholder="<?= quaeriva_t($translator, 'topics.comment_placeholder') ?>"></textarea>
            <button class="button button-small" type="submit" style="margin-block-start:0.75rem;"><?= quaeriva_t($translator, 'topics.comment_submit') ?></button>
          </form>
        </div>
      <?php endif; ?>
    </section>
  </div>
</section>
