<?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" style="padding-block: 2.5rem 4rem;">
  <div class="container" style="max-inline-size: 52rem;">
    <div style="margin-block-end: 2rem; border-block-end: 1px solid #EAE3D5; padding-block-end: 1.5rem;">
      <h1 style="margin:0 0 1rem 0; font-size:1.875rem; font-weight:800; color:#1F1D1A;"><?= 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; border:1px solid #EAE3D5; border-radius:var(--radius-md); padding:0.5rem 0.75rem;">
        <button class="button" 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'] ?? '')));
          $bodyText = strip_tags((string) ($item['body'] ?? ''));
          $wordCount = max(1, count(preg_split('/\s+/u', $bodyText, -1, PREG_SPLIT_NO_EMPTY) ?: []));
          $readingMinutes = max(1, (int) ceil($wordCount / 180));
        ?>
          <article class="hikaya-story-card">
            <h2 class="hikaya-story-title"><a dir="auto" href="<?= quaeriva_escape($itemUrl) ?>"><?= quaeriva_escape((string) ($item['title'] ?? '')) ?></a></h2>
            <p class="hikaya-story-excerpt" dir="auto"><?= quaeriva_escape(mb_strimwidth($bodyText, 0, 220, '…', 'UTF-8')) ?></p>
            <div class="hikaya-story-meta">
              <span class="hikaya-reading-time">⏱ <?= $readingMinutes ?> <?= quaeriva_t($translator, 'common.minutes') ?></span>
              <span class="badge"><?= quaeriva_t($translator, $isQ ? 'common.questions' : 'topics.eyebrow') ?></span>
            </div>
          </article>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>
</section>
