<?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));
$authorName = trim((string) ($topic['author_name'] ?? ''));
$authorUsername = trim((string) ($topic['author_username'] ?? ''));
$authorAvatar = trim((string) ($topic['author_avatar_url'] ?? ''));
if ($authorAvatar === '' && $authorName !== '') {
  $authorAvatar = quaeriva_default_avatar_url((int) ($topic['user_id'] ?? 0));
}
$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: 52rem;">
    <?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="zenith-question-wrap" style="margin-block-end:2rem;">
      <div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:0.5rem; margin-block-end:1rem;">
        <div style="display:flex; align-items:center; gap:0.75rem;">
          <?php if ($authorName !== '' && $authorUsername !== ''): ?>
            <a class="author-chip" href="<?= quaeriva_escape(quaeriva_url('u/' . rawurlencode($authorUsername))) ?>" style="font-weight:700;">
              <?php if ($authorAvatar !== ''): ?><img src="<?= quaeriva_escape($authorAvatar) ?>" alt="" width="32" height="32" style="border-radius:50%;" loading="lazy"><?php endif; ?>
              <bdi><?= quaeriva_escape($authorName) ?></bdi>
            </a>
          <?php endif; ?>
          <span style="font-size:0.8125rem; color:var(--color-muted);"><time datetime="<?= quaeriva_escape((string) ($topic['created_at'] ?? '')) ?>"><?= quaeriva_escape(quaeriva_relative_time($topic['created_at'] ?? '', $translator)) ?></time></span>
        </div>

        <?php if (trim((string) ($topic['category_slug'] ?? '')) !== ''): ?>
          <a class="zenith-badge-category" href="<?= quaeriva_escape(quaeriva_url('c/' . rawurlencode((string) $topic['category_slug']))) ?>"><?= quaeriva_escape($topic['category_name'] ?? '') ?></a>
        <?php endif; ?>
      </div>

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

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

      <div class="action-row" style="margin-block-start:1.5rem; padding-block-start:1rem; border-block-start:1px solid var(--color-border); display:flex; gap:0.5rem; align-items:center;">
        <?php if (($site['follows_enabled'] ?? true) === true): ?>
          <?php if ($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="button button-small <?= !empty($isFollowing) ? 'button-active' : 'button-secondary' ?>" type="submit"><?= quaeriva_icon('bookmark') ?> <?= quaeriva_t($translator, !empty($isFollowing) ? 'topics.unfollow' : 'topics.follow') ?></button>
            </form>
          <?php endif; ?>
        <?php endif; ?>

        <?php if ($currentUser !== null && !$isReported): ?>
          <details class="report-action" style="margin-inline-start:auto;">
            <summary class="button button-small button-secondary"><?= quaeriva_icon('flag') ?> <?= 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>
    </article>

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

      <?php if (($comments ?? []) !== []): ?>
        <div style="display:flex; flex-direction:column; gap:1rem; margin-block-end:2rem;">
          <?php foreach ($comments as $comment):
            $commentId = (int) ($comment['id'] ?? 0);
            $cAuthor = trim((string) ($comment['author_name'] ?? ''));
            $cUsername = trim((string) ($comment['author_username'] ?? ''));
            $cAvatar = trim((string) ($comment['author_avatar_url'] ?? ''));
            if ($cAvatar === '' && $cAuthor !== '') {
              $cAvatar = quaeriva_default_avatar_url((int) ($comment['user_id'] ?? 0));
            }
          ?>
            <article id="comment-<?= $commentId ?>" style="background:var(--color-surface); border:1px solid var(--color-border); border-radius:var(--radius-lg); padding:1.25rem; box-shadow:var(--shadow-sm);">
              <div style="display:flex; align-items:center; gap:0.5rem; margin-block-end:0.75rem;">
                <?php if ($cAuthor !== '' && $cUsername !== ''): ?>
                  <a class="author-inline" href="<?= quaeriva_escape(quaeriva_url('u/' . rawurlencode($cUsername))) ?>" style="font-weight:600;">
                    <?php if ($cAvatar !== ''): ?><img src="<?= quaeriva_escape($cAvatar) ?>" alt="" width="24" height="24" style="border-radius:50%;" loading="lazy"><?php endif; ?>
                    <bdi><?= quaeriva_escape($cAuthor) ?></bdi>
                  </a>
                <?php endif; ?>
                <span style="font-size:0.75rem; color:var(--color-muted);"><time datetime="<?= quaeriva_escape((string) ($comment['created_at'] ?? '')) ?>"><?= quaeriva_escape(quaeriva_relative_time($comment['created_at'] ?? '', $translator)) ?></time></span>
              </div>
              <div class="rich-text" dir="<?= quaeriva_escape($contentDirection) ?>" style="line-height:1.65;">
                <?= quaeriva_rich_text($comment['body'] ?? '', 'comment') ?>
              </div>
            </article>
          <?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-lg); padding:1.5rem;">
          <h3 style="font-size:1.125rem; margin:0 0 1rem 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" type="submit" style="margin-block-start:1rem;"><?= quaeriva_t($translator, 'topics.comment_submit') ?></button>
          </form>
        </div>
      <?php else: ?>
        <p class="notice notice-muted"><?= quaeriva_t($translator, 'topics.login_to_comment') ?></p>
      <?php endif; ?>
    </section>
  </div>
</section>
