<?php

declare(strict_types=1);

// Variables provided by site/routes/index.php:
// $basePath, $resolvedPath, $currentUser, $requestUri

if (!function_exists('myronSiteEscape')) {
    function myronSiteEscape(string $value): string
    {
        return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
    }
}

$queryRaw = trim((string) ($_GET['q'] ?? ''));
$limitInput = (int) ($_GET['limit'] ?? 20);
$isDevEnv = (string) (getenv('MYRON_APP_ENV') ?: '') === 'local';
$search = myronPublicSearchRequestService()->search($queryRaw, $limitInput, $isDevEnv);
$limitInput = (int) $search['limit'];
$results = (array) $search['results'];
$total = (int) $search['total'];
$searchUnavailable = (bool) $search['unavailable'];
$searchTransientError = (bool) $search['transientError'];
$searchExceptionDetails = (string) $search['exceptionDetails'];

$navigationByPlacement = $repository->listPublishedMenuNavigationByPlacements(['primary'], ['footer']);
$navigation = $navigationByPlacement['trees']['primary'] ?? [];
$footerNavigation = $navigationByPlacement['flat']['footer'] ?? [];
$headerContext = myronPublicHeaderContextResolver()->resolve(null, $resolvedPath, $navigation);

?>
<!DOCTYPE html>
<html lang="<?= myronSiteEscape(myronSiteLanguage()) ?>" data-appearance-default="light" data-appearance-policy="auto" data-appearance-system-follow="false">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= $queryRaw !== '' ? 'Search: ' . myronSiteEscape($queryRaw) : 'Search' ?></title>
  <meta name="description" content="Search results across published content.">
  <meta name="robots" content="noindex,follow">
  <?= myronRenderSiteFaviconLink() . "\n" ?>
  <?= myronRenderDefinitionFontHeadTags() . "\n" ?>
  <link rel="stylesheet" href="<?= myronSiteEscape(myronBuildAssetUrl('runtime/css/tokens.css')) ?>">
  <link rel="stylesheet" href="<?= myronSiteEscape(myronBuildAssetUrl('runtime/css/runtime-fonts.css')) ?>">
  <?= myronCustomCssRepository()->renderCustomFontHeadTags() . "\n" ?>
  <link rel="stylesheet" href="<?= myronSiteEscape(myronBuildAssetUrl('runtime/css/runtime-token-overrides.css')) ?>">
  <link rel="stylesheet" href="<?= myronSiteEscape(myronBuildAssetUrl('runtime/css/base.css')) ?>">
  <link rel="stylesheet" href="<?= myronSiteEscape(myronBuildAssetUrl('runtime/css/components.css')) ?>">
  <link rel="stylesheet" href="<?= myronSiteEscape(myronBuildAssetUrl('runtime/css/public-site.css')) ?>">
  <?= myronCustomCssRepository()->renderSiteStyleTag(MyronCustomCssRepository::CONTEXT_PUBLIC) . "\n" ?>
  <script src="<?= myronSiteEscape(myronBuildAssetUrl('runtime/js/interactive-atoms.min.js')) ?>" defer></script>
  <script src="<?= myronSiteEscape(myronBuildAssetUrl('runtime/js/public-navigation.js')) ?>" defer></script>
</head>
<body class="<?= is_array($currentUser) ? 'myron-site-page myron-site-page--authenticated' : 'myron-site-page' ?>">
  <?php if (is_array($currentUser)): ?>
  <?php myronRenderPublicShellHeader($currentUser, ['logoutReturnTo' => $requestUri]); ?>
  <?php endif; ?>
  <div class="myron-site">
    <?= myronPublicNavigationRenderer()->renderContext($headerContext, $basePath, '/search') . "\n" ?>

    <main class="myron-site__canvas">
      <section class="myron-public-search">
        <header class="myron-public-search__header">
          <h1 class="myron-heading">Search</h1>
          <form class="myron-public-search__form" action="/search" method="get" role="search">
            <label class="myron-public-search__label" for="myron-public-search-input">Search the site</label>
            <input
              id="myron-public-search-input"
              class="myron-input myron-public-search__input"
              type="search"
              name="q"
              value="<?= myronSiteEscape($queryRaw) ?>"
              placeholder="Search published content…"
              autocomplete="off"
              autofocus>
            <button type="submit" class="myron-button myron-button--intent-primary myron-button--size-md">Search</button>
          </form>
        </header>

        <?php if ($searchUnavailable): ?>
        <p class="myron-paragraph myron-paragraph--muted myron-public-search__error">
          Search isn&rsquo;t available on this site yet. An administrator needs to apply pending updates.
        </p>
        <?php elseif ($searchTransientError): ?>
        <p class="myron-paragraph myron-paragraph--muted myron-public-search__error">Search is temporarily unavailable. Please try again.</p>
        <?php if ($isDevEnv && $searchExceptionDetails !== ''): ?>
        <details class="myron-public-search__dev-details">
          <summary>Developer details</summary>
          <pre><?= myronSiteEscape($searchExceptionDetails) ?></pre>
        </details>
        <?php endif; ?>
        <?php elseif ($queryRaw === ''): ?>
        <p class="myron-paragraph myron-paragraph--muted myron-public-search__empty">Enter a query above to search published pages.</p>
        <?php elseif ($results === []): ?>
        <p class="myron-paragraph myron-paragraph--muted myron-public-search__empty">
          No results for <strong><?= myronSiteEscape($queryRaw) ?></strong>.
        </p>
        <?php else: ?>
        <p class="myron-paragraph myron-paragraph--muted myron-public-search__summary">
          <?= (int) $total ?> result<?= $total === 1 ? '' : 's' ?> for <strong><?= myronSiteEscape($queryRaw) ?></strong>.
        </p>
        <ol class="myron-public-search__results" role="list">
          <?php foreach ($results as $hit): ?>
          <?php
            $title = (string) ($hit['title'] ?? 'Untitled');
            $url = (string) ($hit['url'] ?? '');
            $path = (string) ($hit['path'] ?? '/');
            // For internal navigation, prefer relative path; fall back to absolute URL.
            $href = $path !== '' ? $path : $url;
            // Snippet is service-built: already HTML-escaped with <mark> wrappers.
            $snippet = (string) ($hit['snippet'] ?? '');
          ?>
          <li class="myron-public-search__result">
            <a class="myron-public-search__result-link" href="<?= myronSiteEscape($href) ?>">
              <h2 class="myron-heading myron-public-search__result-title"><?= myronSiteEscape($title) ?></h2>
            </a>
            <p class="myron-public-search__result-url"><?= myronSiteEscape($href) ?></p>
            <?php if ($snippet !== ''): ?>
            <p class="myron-paragraph myron-public-search__result-snippet"><?= $snippet ?></p>
            <?php endif; ?>
          </li>
          <?php endforeach; ?>
        </ol>
        <?php endif; ?>
      </section>
    </main>
  </div>
  <?= myronCustomCssRepository()->renderCustomInteractionsScriptTags() . "\n" ?>
</body>
</html>
