<?php
declare(strict_types=1);
// Hikaya keeps its reading-first presentation, but the full interaction set is
// required: without the answer form, votes, comments and pagination a member
// cannot take part at all.
$questionTags = is_array($questionTags ?? null) ? $questionTags : [];
$reportedItems = is_array($reportedItems ?? null) ? $reportedItems : ['question' => [], 'answer' => [], 'comment' => []];
$contentDirection = $question !== null ? $localeContext->contentDirection($question['content_locale'] ?? null) : $localeContext->htmlAttributes()['dir'];
$reportReasons = ['spam', 'abuse', 'duplicate', 'misleading', 'other'];
$postingRules = is_array($postingRules ?? null)
    ? array_replace(\App\Community\PostingPolicyService::defaults(), $postingRules)
    : \App\Community\PostingPolicyService::defaults();
$commentMin = max(0, (int) ($postingRules['comment_min'] ?? 3));
$commentMax = max(0, (int) ($postingRules['comment_max'] ?? 600));
$answerMin = max(0, (int) ($postingRules['answer_min'] ?? 10));
$answerMax = max(0, (int) ($postingRules['answer_max'] ?? 20000));
$questionViewUrl = quaeriva_question_url((string) $slug, (int) ($question['id'] ?? 0));
$questionActionBase = quaeriva_question_action_url((string) $slug);
$answersMeta = is_array($answersMeta ?? null) ? $answersMeta : ['page' => 1, 'per_page' => 50, 'total' => count($answers ?? []), 'total_pages' => 1];
$answerPage = max(1, (int) ($answersMeta['page'] ?? 1));
$answerPages = max(1, (int) ($answersMeta['total_pages'] ?? 1));
// The heading reports the total across pages, not the slice rendered here.
$answerTotal = max(0, (int) ($answersMeta['total'] ?? count($answers ?? [])));
$answersList = is_array($answers ?? null) ? $answers : [];
$questionComments = is_array($comments['question'] ?? null) ? $comments['question'] : [];
$answerComments = is_array($comments['answers'] ?? null) ? $comments['answers'] : [];
$currentUserId = (int) ($currentUser['id'] ?? 0);
$questionOwnerId = (int) ($question['user_id'] ?? 0);
$questionSidebar = isset($renderSection) && is_callable($renderSection) ? $renderSection('question_sidebar') : '';
$bodyText = trim(strip_tags((string) ($question['body'] ?? '')));
$words = preg_split('/\s+/u', $bodyText, -1, PREG_SPLIT_NO_EMPTY) ?: [];
$readingMinutes = max(1, (int) ceil(count($words) / 180));
?>
<div class="hikaya-reading-bar" id="hikayaReadingProgress"></div>

<section class="content-section hikaya-reader">
  <div class="container hikaya-reader-container<?= $questionSidebar !== '' ? ' has-sidebar' : '' ?>">
    <?php if ($questionSidebar !== ''): ?><aside class="content-sidebar"><?= $questionSidebar ?></aside><?php endif; ?>

    <?php if ($question === null): ?>
      <div class="empty-state">
        <h1><?= quaeriva_t($translator, 'questions.not_found') ?></h1>
        <p><?= quaeriva_t($translator, 'questions.not_found_hint') ?></p>
        <a class="button button-secondary" href="<?= quaeriva_escape(quaeriva_url()) ?>"><?= quaeriva_t($translator, 'common.back_home') ?></a>
      </div>
    <?php else: ?>
      <?php if (trim((string) ($notice ?? '')) !== ''): ?>
        <div class="notice" role="status"><?= quaeriva_escape($notice) ?></div>
      <?php endif; ?>

      <?php
        $questionAuthor = trim((string) ($question['author_name'] ?? ''));
        $questionUsername = trim((string) ($question['author_username'] ?? ''));
        $isQuestionReported = in_array((int) ($question['id'] ?? 0), array_map('intval', (array) ($reportedItems['question'] ?? [])), true);
      ?>

      <header class="hikaya-reader-head">
        <div class="hikaya-reader-kicker">
          <span class="hikaya-reading-time">⏱ <?= (int) $readingMinutes ?> <?= quaeriva_t($translator, 'common.reading_minutes') ?></span>
          <?php if (!empty($question['category_slug'])): ?>
            <a class="badge" href="<?= quaeriva_escape(quaeriva_url('c/' . rawurlencode((string) $question['category_slug']))) ?>"><?= quaeriva_escape((string) ($question['category_name'] ?? '')) ?></a>
          <?php endif; ?>
        </div>
        <h1 dir="<?= quaeriva_escape($contentDirection) ?>"><?= quaeriva_escape((string) ($question['title'] ?? '')) ?></h1>
        <div class="hikaya-reader-byline">
          <?php if ($questionUsername !== ''): ?>
            <a href="<?= quaeriva_escape(quaeriva_url('u/' . rawurlencode($questionUsername))) ?>"><?= quaeriva_escape($questionAuthor !== '' ? $questionAuthor : $questionUsername) ?></a>
          <?php else: ?>
            <span><?= quaeriva_t($translator, 'common.anonymous') ?></span>
          <?php endif; ?>
          <span>·</span>
          <time datetime="<?= quaeriva_escape((string) ($question['created_at'] ?? '')) ?>"><?= quaeriva_escape(quaeriva_relative_time($question['created_at'] ?? '', $translator)) ?></time>
        </div>
      </header>

      <article class="rich-text hikaya-reader-body" dir="<?= quaeriva_escape($contentDirection) ?>">
        <?= quaeriva_rich_text($question['body'] ?? '', 'full') ?>
      </article>

      <?php if ($questionTags !== []): ?>
        <div class="hikaya-tags">
          <?php foreach ($questionTags as $tag): ?>
            <a href="<?= quaeriva_escape(quaeriva_url('t/' . rawurlencode((string) ($tag['slug'] ?? '')))) ?>"><?= quaeriva_escape((string) ($tag['name'] ?? '')) ?></a>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>

      <div class="action-row hikaya-question-actions">
        <div class="vote-controls">
          <strong><?= (int) ($question['votes_count'] ?? 0) ?></strong>
          <?php if ($currentUser !== null && ($questionOwnerId <= 0 || $questionOwnerId !== $currentUserId)): ?>
            <form method="post" action="<?= quaeriva_escape($questionActionBase . '/vote') ?>">
              <input type="hidden" name="_csrf" value="<?= quaeriva_escape($csrfToken) ?>">
              <input type="hidden" name="answers_page" value="<?= (int) $answerPage ?>">
              <button class="button button-small button-secondary" type="submit" name="value" value="1"><?= quaeriva_t($translator, 'questions.vote_up') ?></button>
              <button class="button button-small button-secondary" type="submit" name="value" value="-1"><?= quaeriva_t($translator, 'questions.vote_down') ?></button>
            </form>
          <?php elseif ($currentUser === null): ?>
            <a class="text-link" href="<?= quaeriva_escape(quaeriva_url('login', ['redirect' => $questionViewUrl])) ?>"><?= quaeriva_t($translator, 'questions.login_to_vote') ?></a>
          <?php endif; ?>
        </div>

        <?php if ($currentUser !== null): ?>
          <form method="post" action="<?= quaeriva_escape($questionActionBase . '/follow') ?>">
            <input type="hidden" name="_csrf" value="<?= quaeriva_escape($csrfToken) ?>">
            <button class="button button-small button-secondary" type="submit"><?= quaeriva_t($translator, !empty($isFollowing) ? 'questions.unfollow' : 'questions.follow') ?></button>
          </form>

          <?php if ($isQuestionReported): ?>
            <span class="report-done"><?= quaeriva_t($translator, 'questions.report_done') ?></span>
          <?php else: ?>
            <details class="report-action">
              <summary class="button button-small button-secondary"><?= quaeriva_t($translator, 'questions.report_question') ?></summary>
              <form class="compact-form report-popover" method="post" action="<?= quaeriva_escape($questionActionBase . '/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 button-secondary" type="submit"><?= quaeriva_t($translator, 'questions.report_submit') ?></button>
              </form>
            </details>
          <?php endif; ?>
        <?php endif; ?>
      </div>

      <?php if ($questionComments !== []): ?>
        <section class="hikaya-comments">
          <h3><?= quaeriva_t($translator, 'questions.comments') ?></h3>
          <?php foreach ($questionComments as $comment): ?>
            <div class="hikaya-comment" dir="auto">
              <?= quaeriva_rich_text($comment['body'] ?? '', 'comment') ?>
              <span class="hikaya-comment-meta"><?= quaeriva_escape(trim((string) ($comment['author_name'] ?? '')) ?: $translator->get('common.anonymous')) ?></span>
            </div>
          <?php endforeach; ?>
        </section>
      <?php endif; ?>

      <?php if ($currentUser !== null): ?>
        <form class="compact-form hikaya-comment-form" method="post" action="<?= quaeriva_escape($questionActionBase . '/comments') ?>">
          <input type="hidden" name="_csrf" value="<?= quaeriva_escape($csrfToken) ?>">
          <?= quaeriva_bot_guard_fields() ?>
          <input type="hidden" name="answers_page" value="<?= (int) $answerPage ?>">
          <textarea name="body" rows="2" dir="<?= quaeriva_escape($contentDirection) ?>" required<?= $commentMax > 0 ? ' maxlength="' . (int) $commentMax . '"' : '' ?><?= $commentMin > 0 ? ' minlength="' . (int) $commentMin . '"' : '' ?> placeholder="<?= quaeriva_t($translator, 'questions.comment_placeholder') ?>"></textarea>
          <button class="button button-small" type="submit"><?= quaeriva_t($translator, 'questions.comment') ?></button>
        </form>
      <?php endif; ?>

      <section class="hikaya-answers" id="answers-heading">
        <h2><?= quaeriva_t($translator, 'questions.answers_count', ['count' => (int) $answerTotal]) ?></h2>

        <?php if ($answersList === []): ?>
          <p class="notice notice-muted"><?= quaeriva_t($translator, 'questions.no_answers') ?></p>
        <?php endif; ?>

        <?php foreach ($answersList as $answer):
          $answerId = (int) ($answer['id'] ?? 0);
          $answerOwnerId = (int) ($answer['user_id'] ?? 0);
          $ansDirection = $localeContext->contentDirection($answer['content_locale'] ?? null);
          $ansAuthor = trim((string) ($answer['author_name'] ?? ''));
          $ansUsername = trim((string) ($answer['author_username'] ?? ''));
          $isBest = !empty($answer['is_best']);
          $isAnswerReported = in_array($answerId, array_map('intval', (array) ($reportedItems['answer'] ?? [])), true);
          $canAccept = $currentUser !== null && ($currentUserId === $questionOwnerId || in_array((string) ($currentUser['role'] ?? ''), ['moderator', 'admin'], true));
        ?>
          <article id="answer-<?= $answerId ?>" class="hikaya-answer<?= $isBest ? ' is-best' : '' ?>">
            <?php if ($isBest): ?>
              <div class="best-badge">★ <?= quaeriva_t($translator, 'questions.best_answer') ?></div>
            <?php endif; ?>
            <div class="rich-text" dir="<?= quaeriva_escape($ansDirection) ?>"><?= quaeriva_rich_text($answer['body'] ?? '', 'full') ?></div>

            <div class="action-row hikaya-answer-actions">
              <div class="vote-controls">
                <strong><?= (int) ($answer['votes_count'] ?? 0) ?></strong>
                <?php if ($currentUser !== null && ($answerOwnerId <= 0 || $answerOwnerId !== $currentUserId)): ?>
                  <form method="post" action="<?= quaeriva_escape($questionActionBase . '/answers/' . $answerId . '/vote') ?>">
                    <input type="hidden" name="_csrf" value="<?= quaeriva_escape($csrfToken) ?>">
                    <input type="hidden" name="answers_page" value="<?= (int) $answerPage ?>">
                    <button class="button button-small button-secondary" type="submit" name="value" value="1"><?= quaeriva_t($translator, 'questions.vote_up') ?></button>
                    <button class="button button-small button-secondary" type="submit" name="value" value="-1"><?= quaeriva_t($translator, 'questions.vote_down') ?></button>
                  </form>
                <?php endif; ?>
              </div>

              <?php if ($canAccept && !$isBest && $answerId > 0): ?>
                <form method="post" action="<?= quaeriva_escape($questionActionBase . '/answers/' . $answerId . '/accept') ?>">
                  <input type="hidden" name="_csrf" value="<?= quaeriva_escape($csrfToken) ?>">
                  <input type="hidden" name="answers_page" value="<?= (int) $answerPage ?>">
                  <button class="button button-small button-secondary" type="submit"><?= quaeriva_t($translator, 'questions.accept_answer') ?></button>
                </form>
              <?php endif; ?>

              <?php if ($currentUser !== null && $answerId > 0): ?>
                <?php if ($isAnswerReported): ?>
                  <span class="report-done"><?= quaeriva_t($translator, 'questions.report_done') ?></span>
                <?php else: ?>
                  <details class="report-action">
                    <summary class="button button-small button-secondary"><?= quaeriva_t($translator, 'questions.report_answer') ?></summary>
                    <form class="compact-form report-popover" method="post" action="<?= quaeriva_escape($questionActionBase . '/answers/' . $answerId . '/report') ?>">
                      <input type="hidden" name="_csrf" value="<?= quaeriva_escape($csrfToken) ?>">
                      <input type="hidden" name="answers_page" value="<?= (int) $answerPage ?>">
                      <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($ansDirection) ?>"></textarea>
                      <button class="button button-small button-secondary" type="submit"><?= quaeriva_t($translator, 'questions.report_submit') ?></button>
                    </form>
                  </details>
                <?php endif; ?>
              <?php endif; ?>

              <span class="hikaya-answer-byline">
                <?php if ($ansUsername !== ''): ?>
                  <a href="<?= quaeriva_escape(quaeriva_url('u/' . rawurlencode($ansUsername))) ?>"><?= quaeriva_escape($ansAuthor !== '' ? $ansAuthor : $ansUsername) ?></a>
                <?php else: ?>
                  <?= quaeriva_t($translator, 'common.anonymous') ?>
                <?php endif; ?>
                <time datetime="<?= quaeriva_escape((string) ($answer['created_at'] ?? '')) ?>"><?= quaeriva_escape(quaeriva_relative_time($answer['created_at'] ?? '', $translator)) ?></time>
              </span>
            </div>

            <?php $thisAnswerComments = is_array($answerComments[$answerId] ?? null) ? $answerComments[$answerId] : []; ?>
            <?php if ($thisAnswerComments !== []): ?>
              <div class="hikaya-comments">
                <?php foreach ($thisAnswerComments as $comment): ?>
                  <div class="hikaya-comment" dir="auto">
                    <?= quaeriva_rich_text($comment['body'] ?? '', 'comment') ?>
                    <span class="hikaya-comment-meta"><?= quaeriva_escape(trim((string) ($comment['author_name'] ?? '')) ?: $translator->get('common.anonymous')) ?></span>
                  </div>
                <?php endforeach; ?>
              </div>
            <?php endif; ?>

            <?php if ($currentUser !== null && $answerId > 0): ?>
              <form class="compact-form hikaya-comment-form" method="post" action="<?= quaeriva_escape($questionActionBase . '/answers/' . $answerId . '/comments') ?>">
                <input type="hidden" name="_csrf" value="<?= quaeriva_escape($csrfToken) ?>">
                <?= quaeriva_bot_guard_fields() ?>
                <input type="hidden" name="answers_page" value="<?= (int) $answerPage ?>">
                <textarea name="body" rows="2" dir="<?= quaeriva_escape($ansDirection) ?>" required<?= $commentMax > 0 ? ' maxlength="' . (int) $commentMax . '"' : '' ?><?= $commentMin > 0 ? ' minlength="' . (int) $commentMin . '"' : '' ?> placeholder="<?= quaeriva_t($translator, 'questions.comment_placeholder') ?>"></textarea>
                <button class="button button-small" type="submit"><?= quaeriva_t($translator, 'questions.comment') ?></button>
              </form>
            <?php endif; ?>
          </article>
        <?php endforeach; ?>

        <?php if ($answerPages > 1): ?>
          <nav class="pagination" aria-label="<?= quaeriva_t($translator, 'questions.answers_pagination') ?>">
            <span><?= quaeriva_t($translator, 'questions.answers_page_summary', ['page' => (int) $answerPage, 'pages' => (int) $answerPages]) ?></span>
            <?php if ($answerPage > 1): ?>
              <a class="button button-small button-secondary" href="<?= quaeriva_escape(quaeriva_question_url((string) $slug, (int) ($question['id'] ?? 0), ['answers_page' => $answerPage - 1]) . '#answers-heading') ?>"><?= quaeriva_t($translator, 'questions.previous_page') ?></a>
            <?php endif; ?>
            <?php if ($answerPage < $answerPages): ?>
              <a class="button button-small button-secondary" href="<?= quaeriva_escape(quaeriva_question_url((string) $slug, (int) ($question['id'] ?? 0), ['answers_page' => $answerPage + 1]) . '#answers-heading') ?>"><?= quaeriva_t($translator, 'questions.next_page') ?></a>
            <?php endif; ?>
          </nav>
        <?php endif; ?>
      </section>

      <section class="hikaya-composer">
        <h2><?= quaeriva_t($translator, 'questions.answer_prompt') ?></h2>
        <?php if ($currentUser !== null): ?>
          <form class="question-form" method="post" action="<?= quaeriva_escape($questionActionBase . '/answers') ?>">
            <input type="hidden" name="_csrf" value="<?= quaeriva_escape($csrfToken) ?>">
            <?= quaeriva_bot_guard_fields() ?>
            <textarea id="answer-body" name="body" class="comment-textarea" dir="<?= quaeriva_escape($contentDirection) ?>" rows="7"<?= quaeriva_rich_editor_attributes($translator, 'full', '') ?> required<?= $answerMax > 0 ? ' maxlength="' . (int) $answerMax . '"' : '' ?><?= $answerMin > 0 ? ' minlength="' . (int) $answerMin . '"' : '' ?> placeholder="<?= quaeriva_t($translator, 'questions.answer_placeholder') ?>"></textarea>
            <button class="button" type="submit"><?= quaeriva_t($translator, 'questions.answer_submit') ?></button>
          </form>
        <?php else: ?>
          <p class="notice notice-muted"><?= quaeriva_t($translator, 'questions.login_to_answer') ?></p>
        <?php endif; ?>
      </section>
    <?php endif; ?>
  </div>
</section>

<script>
window.addEventListener('scroll', function () {
  var bar = document.getElementById('hikayaReadingProgress');
  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>
