<?php
declare(strict_types=1);
$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));
$answerTotal = max(0, (int) ($answersMeta['total'] ?? count($answers ?? [])));
$questionSidebar = isset($renderSection) && is_callable($renderSection) ? $renderSection('question_sidebar') : '';
?>

<section class="content-section question-section">
  <div class="container question-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
      $questionAuthor = trim((string) ($question['author_name'] ?? ''));
      $questionUsername = trim((string) ($question['author_username'] ?? ''));
      $questionOwnerId = (int) ($question['user_id'] ?? 0);
      $currentUserId = (int) ($currentUser['id'] ?? 0);
      ?>

      <?php if (trim((string) ($notice ?? '')) !== ''): ?><div class="notice" role="status"><?= quaeriva_escape($notice) ?></div><?php endif; ?>
      <?php if ((string) ($_GET['answer'] ?? '') === 'pending'): ?><div class="notice" role="status"><?= quaeriva_t($translator, 'questions.answer_pending') ?></div><?php endif; ?>
      <?php if ((string) ($_GET['commented'] ?? '') === 'pending'): ?><div class="notice" role="status"><?= quaeriva_t($translator, 'questions.comment_pending') ?></div><?php endif; ?>

      <!-- Reddit-Style Question Box -->
      <article class="orbit-detail-wrap">
        <!-- Vote Rail -->
        <div class="orbit-vote-rail">
          <?php if ($currentUser !== null && ($questionOwnerId <= 0 || $questionOwnerId !== $currentUserId)): ?>
            <form method="post" action="<?= quaeriva_escape($questionActionBase . '/vote') ?>" style="display:flex; flex-direction:column; align-items:center;">
              <input type="hidden" name="_csrf" value="<?= quaeriva_escape($csrfToken) ?>">
              <button class="orbit-pill-btn" type="submit" name="value" value="1" aria-label="<?= quaeriva_t($translator, 'questions.vote_up') ?>" style="padding:0.25rem;">▲</button>
              <strong><?= (int) ($question['votes_count'] ?? 0) ?></strong>
              <button class="orbit-pill-btn" type="submit" name="value" value="-1" aria-label="<?= quaeriva_t($translator, 'questions.vote_down') ?>" style="padding:0.25rem;">▼</button>
            </form>
          <?php else: ?>
            <span class="vote-icon">▲</span>
            <strong><?= (int) ($question['votes_count'] ?? 0) ?></strong>
            <span class="vote-icon">▼</span>
          <?php endif; ?>
        </div>

        <div class="orbit-detail-body">
          <div class="orbit-post-meta" style="margin-block-end:0.75rem;">
            <span>
              <?= quaeriva_t($translator, 'common.author') ?>
              <?php if ($questionAuthor !== '' && $questionUsername !== ''): ?>
                <a href="<?= quaeriva_escape(quaeriva_url('u/' . rawurlencode($questionUsername))) ?>" style="font-weight:700; color:inherit;"><bdi>u/<?= quaeriva_escape($questionUsername) ?></bdi></a>
              <?php else: ?>
                <?= quaeriva_t($translator, 'common.anonymous') ?>
              <?php endif; ?>
            </span>
            <span aria-hidden="true">•</span>
            <time datetime="<?= quaeriva_escape((string) ($question['created_at'] ?? '')) ?>"><?= quaeriva_escape(quaeriva_relative_time($question['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($question['title'] ?? '') ?></h1>

          <?php if ($questionTags !== []): ?>
            <div style="display:flex; gap:0.35rem; flex-wrap:wrap; margin-block-end:1rem;">
              <?php foreach ($questionTags as $tag): $tagSlug = trim((string) ($tag['slug'] ?? '')); if ($tagSlug === '') continue; ?>
                <a class="orbit-flair" href="<?= quaeriva_escape(quaeriva_url('t/' . rawurlencode($tagSlug))) ?>">#<?= quaeriva_escape((string) ($tag['name'] ?? $tagSlug)) ?></a>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>

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

          <!-- Bottom Action Bar -->
          <div class="orbit-action-bar" style="margin-block-start:1.5rem; padding-block-start:0.75rem; border-block-start:1px solid var(--color-border);">
            <span class="orbit-pill-btn">💬 <bdi><?= (int) ($question['answers_count'] ?? count($answers ?? [])) ?></bdi> <?= quaeriva_t($translator, 'common.answers') ?></span>

            <?php if (($site['follows_enabled'] ?? true) === true && $currentUser !== null): ?>
              <form method="post" action="<?= quaeriva_escape($questionActionBase . '/follow') ?>" style="display:inline-flex;">
                <input type="hidden" name="_csrf" value="<?= quaeriva_escape($csrfToken) ?>">
                <button class="orbit-pill-btn" type="submit">🔖 <?= quaeriva_t($translator, !empty($isFollowing) ? 'questions.unfollow' : 'questions.follow') ?></button>
              </form>
            <?php endif; ?>

            <button class="orbit-pill-btn" type="button" data-share-question data-share-url="<?= quaeriva_escape($currentPath ?? $questionViewUrl) ?>">↗ <?= quaeriva_t($translator, 'questions.share') ?></button>
          </div>
        </div>
      </article>

      <!-- Answers List -->
      <section class="answers-section" aria-labelledby="answers-heading">
        <h2 id="answers-heading" style="font-size:1.25rem; font-weight:700; margin-block-end:1rem;">
          <?= quaeriva_t($translator, 'questions.answer_count', ['count' => $answerTotal]) ?>
        </h2>

        <?php if (($answers ?? []) === []): ?>
          <div class="empty-state" style="background:var(--color-surface); border:1px solid var(--color-border); border-radius:var(--radius-sm);"><p><?= quaeriva_t($translator, 'questions.no_answers') ?></p></div>
        <?php else: ?>
          <div class="answer-list" style="display:flex; flex-direction:column; gap:0.75rem;">
            <?php foreach ($answers as $answerIndex => $answer):
              $answerId = (int) ($answer['id'] ?? 0);
              $answerAuthor = trim((string) ($answer['author_name'] ?? ''));
              $answerUsername = trim((string) ($answer['author_username'] ?? ''));
              $answerComments = (array) ($comments['answers'][$answerId] ?? []);
              $isBest = !empty($answer['is_best']);
              $canAccept = $currentUser !== null && (((int) ($currentUser['id'] ?? 0) === (int) ($question['user_id'] ?? 0)) || in_array((string) ($currentUser['role'] ?? ''), ['moderator', 'admin'], true));
            ?>
              <article id="answer-<?= $answerId ?>" class="orbit-detail-wrap <?= $isBest ? 'is-best-answer' : '' ?>" style="<?= $isBest ? 'border-inline-start: 4px solid var(--color-success);' : '' ?>">
                <div class="orbit-vote-rail">
                  <span class="vote-icon">▲</span>
                  <strong><?= (int) ($answer['votes_count'] ?? 0) ?></strong>
                  <span class="vote-icon">▼</span>
                </div>

                <div class="orbit-detail-body">
                  <div class="orbit-post-meta" style="margin-block-end:0.5rem;">
                    <span>
                      <?php if ($answerAuthor !== '' && $answerUsername !== ''): ?>
                        <a href="<?= quaeriva_escape(quaeriva_url('u/' . rawurlencode($answerUsername))) ?>" style="font-weight:700; color:inherit;"><bdi>u/<?= quaeriva_escape($answerUsername) ?></bdi></a>
                      <?php else: ?>
                        <?= quaeriva_t($translator, 'common.anonymous') ?>
                      <?php endif; ?>
                    </span>
                    <span aria-hidden="true">•</span>
                    <time datetime="<?= quaeriva_escape((string) ($answer['created_at'] ?? '')) ?>"><?= quaeriva_escape(quaeriva_relative_time($answer['created_at'] ?? '', $translator)) ?></time>
                    <?php if ($isBest): ?>
                      <span class="orbit-flair is-best"><?= quaeriva_t($translator, 'questions.best_answer') ?></span>
                    <?php endif; ?>
                  </div>

                  <div class="rich-text" dir="<?= quaeriva_escape($contentDirection) ?>">
                    <?= quaeriva_rich_text($answer['body'] ?? '', 'full') ?>
                  </div>

                  <div class="orbit-action-bar" style="margin-block-start:0.75rem;">
                    <?php if ($canAccept && empty($answer['is_best']) && $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="<?= $answerPage ?>">
                        <button class="orbit-pill-btn" type="submit">✔ <?= quaeriva_t($translator, 'questions.accept_answer') ?></button>
                      </form>
                    <?php endif; ?>
                  </div>

                  <!-- Thread Comments -->
                  <?php if (($site['comments_enabled'] ?? true) === true && $answerComments !== []): ?>
                    <div style="margin-block-start:0.75rem;">
                      <?php foreach ($answerComments as $c): ?>
                        <div class="orbit-thread-comment">
                          <div style="font-size:0.75rem; color:var(--color-muted); margin-block-end:0.25rem;">
                            <strong>u/<?= quaeriva_escape(trim((string) ($c['author_name'] ?? '')) ?: $translator->get('common.anonymous')) ?></strong>
                            <span aria-hidden="true">•</span>
                            <time datetime="<?= quaeriva_escape((string) ($c['created_at'] ?? '')) ?>"><?= quaeriva_escape(quaeriva_relative_time($c['created_at'] ?? '', $translator)) ?></time>
                          </div>
                          <div class="rich-text" dir="<?= quaeriva_escape($contentDirection) ?>" style="font-size:0.875rem;">
                            <?= quaeriva_rich_text($c['body'] ?? '', 'comment') ?>
                          </div>
                        </div>
                      <?php endforeach; ?>
                    </div>
                  <?php endif; ?>
                </div>
              </article>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </section>

      <!-- Answer Composer -->
      <section class="answer-composer" style="margin-block-start: 1.5rem; background:var(--color-surface); border:1px solid var(--color-border); border-radius:var(--radius-sm); padding:1.25rem;">
        <h3 style="font-size:1.125rem; margin:0 0 1rem 0;"><?= quaeriva_t($translator, 'questions.answer_prompt') ?></h3>
        <?php if ($currentUser !== null): ?>
          <form method="post" action="<?= quaeriva_escape($questionActionBase . '/answers') ?>">
            <input type="hidden" name="_csrf" value="<?= quaeriva_escape($csrfToken) ?>">
            <?= quaeriva_bot_guard_fields() ?>
            <textarea name="body" class="comment-textarea" dir="<?= quaeriva_escape($contentDirection) ?>" rows="5"<?= quaeriva_rich_editor_attributes($translator, 'full', '') ?> required placeholder="<?= quaeriva_t($translator, 'questions.answer_placeholder') ?>"></textarea>
            <button class="button" type="submit" style="margin-block-start:0.75rem;"><?= 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>
