<?php
declare(strict_types=1);

use Magento\Framework\Escaper;
use Magento\Framework\View\Element\Template;
use Magento\Search\Helper\Data as SearchHelper;
use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\HeroiconsOutline;

// phpcs:disable Magento2.Templates.ThisInTemplate.FoundHelper

/** @var Escaper $escaper */
/** @var Template $block */

/** @var ViewModelRegistry $viewModels */

/** @var SearchHelper $helper */
$helper = $this->helper(SearchHelper::class);

/** @var HeroiconsOutline $heroicons */
$heroicons = $viewModels->require(HeroiconsOutline::class);

/** @var \FoundationCommerce\ThemeViewModels\ViewModels\ThemeIcons $icons */
$icons = $viewModels->require(\FoundationCommerce\ThemeViewModels\ViewModels\ThemeIcons::class);
?>
<script>
    'use strict';

    function initMiniSearch() {
        return {
            minSearchLength: 3,
            suggestions: [],
            suggest() {
                const term = this.$refs.searchInput.value;
                if (term.length >= this.minSearchLength) {
                    this.fetchSuggestions(term);
                } else {
                    this.suggestions = [];
                }
            },
            fetchSuggestions(term) {
                fetch(
                    window.BASE_URL + 'search/ajax/suggest?' + new URLSearchParams({q: term}),
                    {
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest'
                        }
                    }
                )
                .then(response => response.json())
                .then(result => this.suggestions = result);
            },
            search(term) {
                this.$refs.searchInput.value = term;
                document.getElementById('search_mini_form').submit();
            },
            focusElement(element) {
                if (element && element.nodeName === "DIV") {
                    element.focus();
                    return true;
                } else {
                    return false;
                }
            }
        }
    }
</script>
<div class="py-2 mx-auto text-black" x-data="initMiniSearch()">
     <form class="form minisearch" id="search_mini_form"
          action="<?= $escaper->escapeUrl($helper->getResultUrl()) ?>" method="get">
        <label class="hidden" for="search" data-role="minisearch-label">
            <span><?= $escaper->escapeHtml(__('Search')) ?></span>
        </label>
        <input id="search"
               x-ref="searchInput"
               type="search"
               autocomplete="off"
               name="<?= $escaper->escapeHtmlAttr($helper->getQueryParamName()) ?>"
               value="<?= $escaper->escapeHtmlAttr($helper->getEscapedQueryText()) ?>"
               placeholder="<?= $escaper->escapeHtmlAttr(__('Search store...')) ?>"
               maxlength="<?= $escaper->escapeHtmlAttr($helper->getMaxQueryLength()) ?>"
               class="w-full py-2 pl-3 pr-10 text-base leading-normal transition appearance-none text-grey-800
                focus:outline-none focus:border-transparent rounded-full h-9 border-secondary"
               @focus.once="suggest"
               @input.debounce.300="suggest"
               @keydown.arrow-down.prevent="focusElement($el.querySelector('[tabindex]'))"
        />
         <template x-if="suggestions.length > 0">
             <div class="w-full leading-normal transition appearance-none text-grey-800 flex flex-col mt-1">
                 <template x-for="suggestion in suggestions">
                     <div class="flex justify-between p-2 bg-container-lighter even:bg-container mb-1 cursor-pointer
                                 border border-container hover:bg-container-darker"
                          tabindex="0"
                          @click="search(suggestion.title)"
                          @keydown.enter="search(suggestion.title)"
                          @keydown.arrow-up.prevent="
                              focusElement($event.target.previousElementSibling) || $refs.searchInput.focus()
                          "
                          @keydown.arrow-down.prevent="focusElement($event.target.nextElementSibling)"
                     >
                         <span x-text="suggestion.title"></span>
                         <span x-text="suggestion.num_results"></span>
                     </div>
                 </template>
             </div>
         </template>
        <button type="submit"
                title="<?= $escaper->escapeHtml(__('Search')) ?>"
                class="action search absolute top-4 right-4"
                aria-label="Search"
        >
        <?= $icons->newSearchHtml(
                    "hover:text-black text-secondary",
                    22,
                    22
                ) ?>
        </button>
    </form>
</div>
