<?php

use Algolia\AlgoliaSearch\Block\Algolia;
use Blackbird\HyvaAlgoliaSearch\ViewModel\InstantSearchViewModel;
use Hyva\Theme\Model\ViewModelRegistry;
use Magento\Framework\Escaper;

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

$config = $block->getConfigHelper();

$catalogSearchHelper = $block->getCatalogSearchHelper();

/** @var InstantSearchViewModel $viewModel */
$viewModel = $viewModels->require(InstantSearchViewModel::class);
?>
<?php if ($config->isDefaultSelector() && $config->isInstantEnabled()): ?>
    <?= $block->getChildHtml('insights-js') ?>
    <script>
        window.algoliaConfig = <?= /** @noEscape */ $viewModel->getJsConfig(); ?>;

        let autocompleteInitialized = false;
        let commonInitialized = false;
        let insightsInitialized = false;

        async function initAutocomplete() {
            if (autocompleteInitialized) {
                return
            }

            autocompleteInitialized = true;
            Promise.all([
                <?php foreach($viewModel->getAutocompleteScripts() as $script) :?>
                blackbird.loadExternalResource("<?= $script ?>"),
                <?php endforeach; ?>]
            ).then(data => {
                initCommon();
                initAlgoliaInsights();
                initAlgoliaAutocomplete();
            });
        }

        function initInstantSearch() {
            Promise.all([
                <?php foreach($viewModel->getInstantsearchScripts() as $script) :?>
                blackbird.loadExternalResource("<?= $script ?>"),
                <?php endforeach; ?>]
            ).then(data => {
                initCommon();
                initAlgoliaInsights();
                initAlgoliaInstantSearch();
            });
        }

        function initRecommended(objectIds) {
            Promise.all([
                <?php foreach($viewModel->getRecommendedScripts() as $script) :?>
                blackbird.loadExternalResource("<?= $script ?>"),
                <?php endforeach; ?>]
            ).then(data => {
                initCommon();
                initBase64();
                initAlgoliaInsights();
                initAlgoliaRecommended('<?= $block->getRequest()->getFullActionName() ?>', objectIds);
            });
        }

        function initCommon() {
            if (commonInitialized) {
                return
            }

            commonInitialized = true
            initAlgoliaCommon();
            initBase64();
            window.dispatchEvent(new CustomEvent('algolia-loaded'));
        }

        if (algoliaConfig.instant.enabled && (algoliaConfig.isCategoryPage || algoliaConfig.isSearchPage)) {
            initInstantSearch();
        }

        <?php if($block->getRequest()->getFullActionName() === 'catalog_product_view'): ?>
        if (algoliaConfig.recommend.enabledFBT || algoliaConfig.recommend.enabledRelated || algoliaConfig.recommend.isTrendItemsEnabledInPDP || algoliaConfig.recommend.isLookingSimilarEnabledInPDP) {
            let objectIds = ["<?= $block->getRequest()->getParam('id') ?>"];
            initRecommended(objectIds);
        }
        <?php endif;?>

        <?php if($block->getRequest()->getFullActionName() === 'checkout_cart_index'): ?>
        if (algoliaConfig.recommend.enabledFBTInCart || algoliaConfig.recommend.enabledRelatedInCart || algoliaConfig.recommend.isTrendItemsEnabledInPCart || algoliaConfig.recommend.isLookingSimilarEnabledInCart) {
            let recommendedLoaded = false;
            window.addEventListener('private-content-loaded', function (event) {
                if (!recommendedLoaded) {
                    let objectIds = ["<?= $block->getRequest()->getParam('id') ?>"];
                    const items = event.detail.data?.cart?.items;
                    objectIds = [];
                    items.forEach(function (item) {
                        objectIds.push(item.product_id);
                    });
                    initRecommended(objectIds);
                    recommendedLoaded = true;
                }
            });
        }
        <?php endif;?>


        let objectIds = ["<?= $block->getRequest()->getParam('id') ?>"];
        <?php if ($block->getRequest()->getFullActionName() === 'checkout_cart_index'): ?>
        window.addEventListener('private-content-loaded', function (event) {
            let objectIds = ["<?= $block->getRequest()->getParam('id') ?>"];
            const items = event.detail.data?.cart?.items;
            objectIds = [];
            items.forEach(function (item) {
                objectIds.push(item.product_id);
            });
        });
        <?php endif; ?>

        if (algoliaConfig.autocomplete.enabled) {
            document.getElementById('menu-search-icon').addEventListener('click', async () => {
                await initAutocomplete();
            },{once: true});
        }

        window.addEventListener('init-algolia-trends', function () {
            initCommon();
            initAlgoliaInsights();
            window.dispatchEvent(new CustomEvent('init-algolia-trends-done'));
        });

        window.addEventListener('init-algolia-LS', function () {
            initCommon();
            initAlgoliaInsights();
            window.dispatchEvent(new CustomEvent('init-algolia-LS-done'));
        });

        window.addEventListener('user-allowed-save-cookie', function () {
            initAlgoliaInsights(true);
        });
    </script>
<?php endif; ?>
