<?php
declare(strict_types=1);
$searchData = is_array($results ?? null) ? $results : [];
$items = is_array($searchData['items'] ?? null) ? $searchData['items'] : [];
$results = $items; // search passes $results as the envelope; the cards below iterate items
$queryStr = trim((string) (($searchData['filters']['q'] ?? '')));
$totalCount = (int) ($searchData['total'] ?? count($items));
?>
<section class="content-section search-results-section">
  <div class="container search-container">
    <div style="border-block-end:1px solid var(--color-border); padding-block-end:1rem; margin-block-end:1rem;">
      <h1 style="margin:0 0 0.75rem 0; font-size:1.5rem; font-weight:600;"><?= quaeriva_t($translator, 'search.results_for', ['query' => $queryStr]) ?></h1>
      <form method="get" action="<?= quaeriva_escape(quaeriva_url('search')) ?>" style="display:flex; gap:0.5rem; max-inline-size:32rem;">
        <input name="q" type="search" value="<?= quaeriva_escape($queryStr) ?>" required placeholder="<?= quaeriva_t($translator, 'common.search_placeholder') ?>" style="flex:1;">
        <button class="button button-small" type="submit"><?= quaeriva_t($translator, 'common.search_submit') ?></button>
      </form>
    </div>

    <?php if ($results === []): ?>
      <div class="empty-state"><p><?= quaeriva_t($translator, 'search.no_results') ?></p></div>
    <?php else: ?>
      <div class="community-feed">
        <?php foreach ($results as $item):
          $isQ = ($item['type'] ?? 'question') === 'question';
          $itemUrl = $isQ
            ? quaeriva_question_url((string) ($item['slug'] ?? ''), (int) ($item['id'] ?? 0))
            : quaeriva_url('d/' . rawurlencode((string) ($item['slug'] ?? '')));
          $votes = (int) ($item['votes_count'] ?? 0);
          $answers = (int) ($item['answers_count'] ?? 0);
          $comments = (int) ($item['comments_count'] ?? 0);
        ?>
          <article class="nexus-row">
            <div class="nexus-stats-col">
              <span class="nexus-stat-item"><strong><?= $isQ ? $votes : $comments ?></strong> <?= quaeriva_t($translator, $isQ ? 'common.votes' : 'topics.comments') ?></span>
              <?php if ($isQ): ?>
                <span class="nexus-stat-item nexus-stat-answers <?= $answers > 0 ? 'has-answers' : '' ?>"><strong><?= $answers ?></strong> <?= quaeriva_t($translator, 'common.answers') ?></span>
              <?php endif; ?>
            </div>
            <div class="nexus-content-col">
              <h3 class="nexus-title"><a dir="auto" href="<?= quaeriva_escape($itemUrl) ?>"><?= quaeriva_escape((string) ($item['title'] ?? '')) ?></a></h3>
              <p class="nexus-excerpt" dir="auto"><?= quaeriva_escape(mb_strimwidth(strip_tags((string) ($item['body'] ?? '')), 0, 180, '…', 'UTF-8')) ?></p>
            </div>
          </article>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>
</section>
