<?php
/**
 * Mageplaza
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Mageplaza.com license that is
 * available through the world-wide-web at this URL:
 * https://www.mageplaza.com/LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade this extension to newer
 * version in the future.
 *
 * @category    Mageplaza
 * @package     Mageplaza_Blog
 * @copyright   Copyright (c) Mageplaza (https://www.mageplaza.com/)
 * @license     https://www.mageplaza.com/LICENSE.txt
 */

use Mageplaza\Blog\Block\Sidebar\Search;
use Magento\Framework\Escaper;

/** @var Search $block */
/** @var Escaper $escaper */
?>
<style>
    .sidebar.sidebar-main:before {
        content: unset;
    }
</style>
<div class="mpblog-search hidden ">
    <div class="field search">
        <label class="label" for="mpblog-search-box" data-role="minisearch-label">
            <span><?= $escaper->escapeHtml(__('Search')) ?></span>
        </label>
        <div class="control">
            <input id="mpblog-search-box"
                   type="text"
                   name="query"
                   value="<?= $escaper->escapeHtmlAttr($block->getRequest()->getParam('query')) ?>"
                   placeholder="<?= $escaper->escapeHtmlAttr(__('Search blogs here...')) ?>"
                   class="input-text"
                   role="combobox"
                   aria-haspopup="false"
                   aria-autocomplete="both"
            />
            <div id="autocomplete-results" class="autocomplete-suggestions" style="display: none;position: absolute;z-index: 100;width: 100%" >
                <!-- Autocomplete results here -->
            </div>
        </div>
    </div>
    <div class="actions">
        <button type="submit" title="<?= $escaper->escapeHtmlAttr(__('Search')) ?>" class="action search">
            <i class="fa fa-search" aria-hidden="true" style="font-size: 16px;margin-top: 5px;"></i>
        </button>
    </div>
</div>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        var visibleImage = <?php echo /** @noEscape */   json_encode($block->getSidebarConfig('search/show_image')); ?>;
        var searchBox    = document.getElementById('mpblog-search-box');
        let minChars =  <?= $block->getSidebarConfig('search/min_chars') ?: 1; ?>;
        searchBox.addEventListener('input', function () {
            var searchTerm = searchBox.value;
            fetchSuggestions(searchTerm);
        });

        function fetchSuggestions (searchTerm) {
            updateAutocompleteResults(<?php echo /** @noEscape */ ($block->getSearchBlogData()); ?>, searchTerm);
        }

        function updateAutocompleteResults (suggestions, searchTerm) {
            var autocompleteResults       = document.getElementById('autocomplete-results');
            autocompleteResults.innerHTML = '';
            if (searchTerm && searchTerm.length >= minChars) {
                if (suggestions.length > 0) {
                    autocompleteResults.style.display = 'block';
                    var existedPost                   = false;
                    var limitPost                     =  <?= $block->getSidebarConfig('search/search_limit') ?: 10; ?>;
                    let checkNumberPostRender = 0;
                    suggestions.forEach(function (suggestion, index) {

                        if (suggestion.value.toLocaleLowerCase().includes(searchTerm.toLowerCase())) {
                            checkNumberPostRender ++;
                            if (checkNumberPostRender > limitPost) {
                                return;
                            }
                            existedPost             = true;
                            var suggestionDiv       = document.createElement('div');
                            suggestionDiv.className = 'mpblog-suggestion';

                            var suggestionDivParrent       = document.createElement('div');
                            suggestionDivParrent.className = 'autocomplete-suggestion list-post-tabs cursor-pointer';

                            if (visibleImage && visibleImage !== '0') {
                                var suggestionLeftDiv       = document.createElement('div');
                                suggestionLeftDiv.className = 'mpblog-suggestion-left';
                                var img                     = document.createElement('img');
                                img.className               = 'img-responsive';
                                img.src                     = suggestion.image;
                                suggestionLeftDiv.appendChild(img);
                                suggestionDiv.appendChild(suggestionLeftDiv);
                            }

                            var suggestionRightDiv       = document.createElement('div');
                            suggestionRightDiv.className = 'mpblog-suggestion-right ' + (visibleImage ? 'image-visible' : '');

                            var productLineDiv         = document.createElement('div');
                            productLineDiv.className   = 'mpblog-product-line mpblog-product-name';
                            productLineDiv.textContent = suggestion.value;
                            suggestionRightDiv.appendChild(productLineDiv);

                            var productDesDiv       = document.createElement('div');
                            productDesDiv.className = 'mpblog-product-des';
                            var shortDesP           = document.createElement('p');
                            shortDesP.className     = 'mpblog-short-des';
                            shortDesP.textContent   = suggestion.desc;
                            productDesDiv.appendChild(shortDesP);

                            suggestionRightDiv.appendChild(productDesDiv);
                            suggestionDiv.appendChild(suggestionRightDiv);
                            suggestionDivParrent.appendChild(suggestionDiv);
                            suggestionDivParrent.addEventListener("click", function () {
                                window.location.href = suggestion.url;
                            });
                            autocompleteResults.appendChild(suggestionDivParrent);
                        }
                    });
                    if (!existedPost) {
                        var suggestionDivParrent       = document.createElement('div');
                        suggestionDivParrent.className = 'autocomplete-suggestion';
                        suggestionDivParrent.innerText = "No results";
                        autocompleteResults.appendChild(suggestionDivParrent);

                    }
                } else {
                    autocompleteResults.style.display = 'none';
                }
            } else {
                autocompleteResults.style.display = 'none';
            }
        }
        searchBox.addEventListener("blur",function (e) {
            setTimeout(() => {
                var autocompleteResults = document.getElementById('autocomplete-results');
                autocompleteResults.style.display = 'none';
            },150);

        });
    });
</script>

