<?php
declare(strict_types=1);

use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\HeroiconsOutline;
use Magento\Framework\Escaper;
use Mirasvit\Search\Block\Result;
use Mirasvit\Search\Service\DebugService;

/**
 * @var Result            $block
 * @var Escaper           $escaper
 * @var ViewModelRegistry $viewModels
 */

$indexes            = $block->getIndexes();
$tabsThreshold      = $block->getTabsThreshold();
$lessThanMinIndexes = [];
$tabsCnt            = 0;
$totalCnt           = 0;
$currentHtml        = $block->getCurrentContent();
$currentHtml        = $block->getCurrentIndexSize() === 0 ? '' : $currentHtml;
$aggregations       = $block->getAggregationData();
$productIndex       = false;
$heroicons          = $viewModels->require(HeroiconsOutline::class);
$categoryDelimiter  = $heroicons->chevronRightHtml('text-gray-600 inline-block', 16, 16);

$liClasses = 'mr-1 py-2';
if ($tabsCnt > 1) {
    $liClasses .= 'my-6';
}
?>

<?php if (!empty($aggregations)) : ?>
    <div class="mst-search-in__wrapper hidden flex-wrap mb-3">
        <span class="mst-search-in__title p-2 mt-1"><?= $escaper->escapeHtml(__('Search In')) ?></span>
        <?php foreach ($aggregations as $data) : ?>
            <a class="mst-search-in__item card ruby text-sm text-gray-500 p-2 m-1"
               href="<?= $escaper->escapeUrl($data['url']) ?>">
                <span class="name">
                    <?=
                    str_replace(
                        ['<i>', '</i>'],
                        '',
                        str_replace(
                            '</i><i>',
                            '</i>' . $categoryDelimiter . '<i>',
                            $escaper->escapeHtml($data['name'], ['i'])
                        )
                    )
                    ?>
                </span>
                <span class="count text-xs">(<?= $escaper->escapeHtml($data['count']) ?>)</span>
            </a>
        <?php endforeach ?>
    </div>
<?php endif ?>

<ul class="mst-search__result-tabs hidden flex-row flex-wrap border-b border-gray-300 <?php if ($tabsCnt > 1): ?>list-none mb-10 pl-0<?php endif; ?>">
    <?php foreach ($indexes as $index):
        if ($index->getIdentifier() === 'catalogsearch_fulltext') {
            $productIndex = $index;
        }

        $collection = $block->getSearchCollection($index);
        $size       = $collection->getSize();
        $totalCnt   += $size;

        DebugService::log($index->getIdentifier(), 'index_identifier');

        if ($size === 0) {
            continue;
        }

        if ($size < $tabsThreshold && $index->getIdentifier() != 'catalogsearch_fulltext') {
            $lessThanMinIndexes[] = $index;
            continue;
        }

        if (empty($currentHtml)) {
            $currentHtml = $block->getContentBlock($index)->toHtml();
        }

        $tabsCnt++;
        if ($index->getTitle() === $block->getCurrentIndex()->getTitle()
            && $index->getStoreId() == $block->getCurrentIndex()->getStoreId()): ?>
            <li class="<?= $liClasses ?>">
                <a class="active px-6 py-3 border border-gray-300 rounded-t border-b border-gray-100 dark:border-gray-700"
                   href="#">
                    <?= $escaper->escapeHtml(__($index->getTitle())) ?>
                </a>
            </li>
        <?php else: ?>
            <li class="<?= $liClasses ?>">
                <a class="px-6 py-3 border border-gray-300 rounded-t bg-gray-100 hover:bg-gray-50 text-gray-400 hover:text-black"
                   href="<?= $block->getIndexUrl($index) ?>">
                    <?= $escaper->escapeHtml(__($index->getTitle())) ?> (<?= $size ?>)
                </a>
            </li>
        <?php endif ?>
    <?php endforeach ?>
</ul>

<?php if ($block->getCurrentIndex()->getIdentifier() === 'catalogsearch_fulltext' && $block->getCurrentIndexSize() > 0): ?>
    <?php if (!empty($lessThanMinIndexes) && $block->getSearchCollection($block->getCurrentIndex())->getCurPage() === 1): ?>
        <div>
            <?php foreach ($lessThanMinIndexes as $index): ?>
                <div class="mst-search__result-index">
                    <div class="mst-search__result-index-title">
                        <?= $escaper->escapeHtml(__($index->getTitle())) ?>
                    </div>

                    <?= $block->getContentBlock($index)->toHtml() ?>
                </div>
            <?php endforeach ?>
        </div>
    <?php endif ?>

    <?php if ($block->getCurrentIndexSize() > 0 || $totalCnt === 0): ?>
        <?= $currentHtml ?>
    <?php endif ?>
<?php else : ?>
    <?= $currentHtml ?>
<?php endif ?>

<?php if ($totalCnt === 0): ?>
    <?= $block->getContentBlock($productIndex)->toHtml(); ?>
    <?= $block->getLayout()->getBlock("mst.search.no_results")->toHtml(); ?>
<?php endif ?>

<?php if ($block->getCurrentIndexSize() === 0 && $tabsCnt > 1): ?>
    <div class="message notice">
        <div><?= $escaper->escapeHtml(__('Please select other tab to see more results')) ?></div>
    </div>
<?php endif ?>

<?php if ($block->isHighlightingEnabled()): ?>
    <?= $block->getChildHtml('mst.highlight.result'); ?>

    <script>
        const highltedElems = '.search.results .product-item-link, .mst-search__index a, .mst-search__index .mst-search__index-content';
        const searchQuery = '<?= $escaper->escapeUrl($block->getRequest()->getParam('q'))?>';

        if (document.querySelectorAll(highltedElems).length) {
            document.querySelectorAll(highltedElems).forEach(function (item) {
                item.innerHTML = highlightMatch(item.innerHTML, searchQuery);
            });
        }
    </script>
<?php endif; ?>
