<?php
declare(strict_types=1);
$contentDirection = $topic !== null ? $localeContext->contentDirection($topic['content_locale'] ?? null) : $localeContext->htmlAttributes()['dir'];
$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));
$topicSlug = (string) ($topic['slug'] ?? '');
$authorUsername = trim((string) ($topic['author_username'] ?? ''));
$commentsList = is_array($comments ?? null) ? $comments : [];
?>
<div class="hikaya-reading-bar" id="hikayaTopicProgress"></div>

<section class="content-section" style="padding-block: 2.5rem 4rem;">
  <div class="container hikaya-reader-container">
    <header style="margin-block-end: 2rem; border-block-end: 1px solid #EAE3D5; padding-block-end: 1.5rem;">
      <div style="display:flex; align-items:center; gap:0.75rem; margin-block-end:0.75rem; font-size:0.875rem;">
        <span class="hikaya-reading-time">⏱ <?= $readingMinutes ?> <?= quaeriva_t($translator, 'common.minutes') ?></span>
        <?php if (!empty($topic['category_slug'])): ?>
          <a class="badge" 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="font-size: 2.25rem; font-weight: 800; line-height: 1.35; color: #1F1D1A; margin: 0 0 1rem 0;">
        <?= quaeriva_escape($topic['title'] ?? '') ?>
      </h1>
      <div style="display:flex; align-items:center; gap:1rem; color:#8A8175; font-size:0.875rem;">
        <span><?= quaeriva_escape($authorUsername ?: $translator->get('common.anonymous')) ?></span>
        <span>·</span>
        <time datetime="<?= quaeriva_escape((string) ($topic['created_at'] ?? '')) ?>"><?= quaeriva_escape(quaeriva_relative_time($topic['created_at'] ?? '', $translator)) ?></time>
      </div>
    </header>

    <article class="rich-text" dir="<?= quaeriva_escape($contentDirection) ?>" style="font-size: 1.125rem; line-height: 1.85; color: #1F1D1A; margin-block-end: 3rem;">
      <?= quaeriva_rich_text($topic['body'] ?? '', 'full') ?>
    </article>

    <!-- Discussion Comments -->
    <section style="border-block-start: 2px solid #EAE3D5; padding-block-start: 2rem;">
      <h2 style="font-size: 1.5rem; font-weight: 700; color: #1F1D1A; margin-block-end: 1.5rem;">
        <?= quaeriva_t($translator, 'topics.comments') ?> (<?= count($commentsList) ?>)
      </h2>

      <?php foreach ($commentsList as $comm):
        $commAuthor = trim((string) ($comm['author_username'] ?? ''));
      ?>
        <div id="comment-<?= (int) ($comm['id'] ?? 0) ?>" style="background:#FFFFFF; border:1px solid #EAE3D5; border-radius:var(--radius-lg); padding:1.25rem; margin-block-end:1rem;">
          <div class="rich-text" dir="<?= quaeriva_escape($contentDirection) ?>" style="font-size:1rem; line-height:1.75; color:#1F1D1A;">
            <?= quaeriva_rich_text($comm['body'] ?? '', 'comment') ?>
          </div>
          <div style="margin-block-start:0.75rem; font-size:0.75rem; color:#8A8175;">
            <strong><?= quaeriva_escape($commAuthor ?: $translator->get('common.anonymous')) ?></strong> · <time datetime="<?= quaeriva_escape((string) ($comm['created_at'] ?? '')) ?>"><?= quaeriva_escape(quaeriva_relative_time($comm['created_at'] ?? '', $translator)) ?></time>
          </div>
        </div>
      <?php endforeach; ?>

      <?php if ($currentUser !== null): ?>
        <div style="margin-block-start: 2rem; background: #FFFFFF; border: 1px solid #EAE3D5; 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="4" required placeholder="<?= quaeriva_t($translator, 'topics.comment_placeholder') ?>" style="inline-size:100%; border:1px solid #EAE3D5; border-radius:var(--radius-md); padding:0.75rem; font-family:inherit;"></textarea>
            <button class="button" type="submit" style="margin-block-start:0.75rem;"><?= quaeriva_t($translator, 'topics.comment_submit') ?></button>
          </form>
        </div>
      <?php endif; ?>
    </section>
  </div>
</section>

<script>
window.addEventListener('scroll', function() {
  var bar = document.getElementById('hikayaTopicProgress');
  if (!bar) return;
  var total = document.documentElement.scrollHeight - document.documentElement.clientHeight;
  var progress = total > 0 ? (window.pageYOffset / total) * 100 : 0;
  bar.style.inlineSize = Math.min(100, Math.max(0, progress)) + '%';
});
</script>
