<?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; ?>

      <!-- Stack Overflow-Style Question Header -->
      <div class="nexus-q-header">
        <h1 dir="<?= quaeriva_escape($contentDirection) ?>" style="margin:0 0 0.5rem 0; font-size:1.625rem; line-height:1.35; font-weight:600;"><?= quaeriva_escape($question['title'] ?? '') ?></h1>
        <div class="nexus-q-meta">
          <span><?= quaeriva_t($translator, 'common.author') ?>: <strong><?= quaeriva_escape($questionAuthor ?: $translator->get('common.anonymous')) ?></strong></span>
          <span><?= quaeriva_t($translator, 'common.views') ?>: <strong><?= (int) ($question['views_count'] ?? 0) ?></strong></span>
          <span><time datetime="<?= quaeriva_escape((string) ($question['created_at'] ?? '')) ?>"><?= quaeriva_escape(quaeriva_relative_time($question['created_at'] ?? '', $translator)) ?></time></span>
        </div>
      </div>

      <!-- Question Body with Stack Vote Rail -->
      <article class="nexus-post-layout">
        <div class="nexus-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; gap:0.25rem;">
              <input type="hidden" name="_csrf" value="<?= quaeriva_escape($csrfToken) ?>">
              <button class="nexus-vote-btn" type="submit" name="value" value="1" aria-label="<?= quaeriva_t($translator, 'questions.vote_up') ?>"><?= quaeriva_icon('thumbs-up') ?></button>
              <span class="nexus-vote-count"><?= (int) ($question['votes_count'] ?? 0) ?></span>
              <button class="nexus-vote-btn" type="submit" name="value" value="-1" aria-label="<?= quaeriva_t($translator, 'questions.vote_down') ?>"><?= quaeriva_icon('thumbs-down') ?></button>
            </form>
          <?php else: ?>
            <span class="nexus-vote-count"><?= (int) ($question['votes_count'] ?? 0) ?></span>
          <?php endif; ?>
        </div>

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

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

          <div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; margin-block-start:1.5rem; padding-block-start:0.75rem; border-block-start:1px solid var(--color-border); font-size:0.8125rem;">
            <div style="display:flex; gap:0.75rem;">
              <button type="button" data-share-question data-share-url="<?= quaeriva_escape($currentPath ?? $questionViewUrl) ?>" style="background:none; border:none; color:var(--color-muted); cursor:pointer;"><?= quaeriva_t($translator, 'questions.share') ?></button>
              <?php if (($site['follows_enabled'] ?? true) === true && $currentUser !== null): ?>
                <form method="post" action="<?= quaeriva_escape($questionActionBase . '/follow') ?>" style="display:inline;">
                  <input type="hidden" name="_csrf" value="<?= quaeriva_escape($csrfToken) ?>">
                  <button type="submit" style="background:none; border:none; color:var(--color-muted); cursor:pointer;"><?= quaeriva_t($translator, !empty($isFollowing) ? 'questions.unfollow' : 'questions.follow') ?></button>
                </form>
              <?php endif; ?>
            </div>

            <!-- Author signature box -->
            <div style="background:#e1ecf4; padding:0.4rem 0.75rem; border-radius:3px; font-size:0.75rem;">
              <span><?= quaeriva_t($translator, 'common.author') ?>:</span>
              <strong><?= quaeriva_escape($questionAuthor ?: $translator->get('common.anonymous')) ?></strong>
            </div>
          </div>
        </div>
      </article>

      <!-- Answers Section -->
      <section class="answers-section" aria-labelledby="answers-heading" style="margin-block-start:2rem;">
        <h2 id="answers-heading" style="font-size:1.375rem; font-weight:600; padding-block-end:0.5rem; border-block-end:1px solid var(--color-border); margin-block-end:1.25rem;">
          <?= quaeriva_t($translator, 'questions.answer_count', ['count' => $answerTotal]) ?>
        </h2>

        <?php if (($answers ?? []) === []): ?>
          <div class="empty-state"><p><?= quaeriva_t($translator, 'questions.no_answers') ?></p></div>
        <?php else: ?>
          <div>
            <?php foreach ($answers as $answerIndex => $answer):
              $answerId = (int) ($answer['id'] ?? 0);
              $answerAuthor = trim((string) ($answer['author_name'] ?? ''));
              $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="nexus-post-layout" style="padding-block-end:1.5rem; border-block-end:1px solid var(--color-border);">
                <div class="nexus-vote-rail">
                  <span class="nexus-vote-count"><?= (int) ($answer['votes_count'] ?? 0) ?></span>
                  <?php if ($isBest): ?>
                    <span class="nexus-check-accepted" title="<?= quaeriva_t($translator, 'questions.best_answer') ?>">✔</span>
                  <?php elseif ($canAccept && $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="button button-small button-secondary" type="submit" title="<?= quaeriva_t($translator, 'questions.accept_answer') ?>" style="margin-block-start:0.5rem; padding:0.2rem 0.4rem; font-size:0.75rem;">✔</button>
                    </form>
                  <?php endif; ?>
                </div>

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

                  <div style="display:flex; justify-content:flex-end; margin-block-start:1rem;">
                    <div style="background:#e1ecf4; padding:0.35rem 0.65rem; border-radius:3px; font-size:0.75rem;">
                      <span><?= quaeriva_t($translator, 'common.author') ?>:</span>
                      <strong><?= quaeriva_escape($answerAuthor ?: $translator->get('common.anonymous')) ?></strong>
                    </div>
                  </div>
                </div>
              </article>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </section>

      <!-- Answer Composer -->
      <section class="answer-composer" style="margin-block-start:2rem;">
        <h2 style="font-size:1.25rem; font-weight:600; margin-block-end:0.75rem;"><?= quaeriva_t($translator, 'questions.answer_prompt') ?></h2>
        <?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="6"<?= 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>
