<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// phpcs:disable PHPCompatibility.Miscellaneous.RemovedAlternativePHPTags.MaybeASPOpenTagFound
/** @var $block \Magento\Catalog\Block\Adminhtml\Product\Edit\Tab\Attributes\Search */
/** @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer */
?>
<div id="product-attribute-search-container" class="suggest-expandable attribute-selector">
    <div class="action-dropdown">
        <button type="button" class="action-toggle action-choose" data-mage-init='{"dropdown":{}}'
                data-toggle="dropdown">
            <span><?= $block->escapeHtml(__('Add Attribute')) ?></span>
        </button>
        <div class="dropdown-menu">
            <input data-role="product-attribute-search"
                   data-group="<?= $block->escapeHtmlAttr($block->getGroupCode()) ?>"
                   class="search" type="text"
                   placeholder="<?= $block->escapeHtmlAttr(__('start typing to search attribute')) ?>" />
        </div>
    </div>

<script data-template-for="product-attribute-search-<?= $block->escapeHtmlAttr($block->getGroupId()) ?>"
        type="text/x-magento-template">
    <ul data-mage-init='{"menu":[]}'>
        <% if (data.items.length) { %>
        <% _.each(data.items, function(value){ %>
        <li <%= data.optionData(value) %>><a href="#"><%- value.label %></a></li>
        <% }); %>
        <% } else { %><span class="mage-suggest-no-records"><%- data.noRecordsText %></span><% } %>
    </ul>
    <div class="actions"><?= $block->escapeHtml($block->getAttributeCreate()) ?></div>
</script>

<?php
/** @var \Magento\Framework\Json\Helper\Data $jsonHelper */
$jsonHelper = $block->getData('jsonHelper');
$selectorOptions = /* @noEscape */ $jsonHelper->jsonEncode($block->getSelectorOptions());
$scriptString = <<<script
    require(["jquery","mage/mage","mage/backend/suggest"], function($) {
        var $suggest = $('[data-role="product-attribute-search"][data-group="{$block->escapeHtml(
            $block->getGroupCode()
        )}"]');

        $suggest.on('suggestclose', function(e) {
            $suggest.closest('.dropdown-menu').siblings('[data-toggle=dropdown]').trigger('close.dropdown');
        });
        $suggest.closest('.dropdown-menu').siblings('[data-toggle=dropdown]').on('click.toggleDropdown', function () {
            if ($(this).hasClass('active')) {
                $suggest.click();
            }
        });

        $('[data-form=edit-product]').on('changeAttributeSet', function(event, data) {
            $suggest.mage('suggest', 'option', 'ajaxOptions', {
                data: {'template_id': data.id}
            });
        });

        $suggest.mage('suggest', {$selectorOptions})
            .on('suggestselect', function (e, ui) {
                $(this).val('');
                var templateId = $('#attribute_set_id').val();
                if (ui.item.id) {
                    $.ajax({
                        url: '{$block->escapeJs($block->getAddAttributeUrl())}',
                        type: 'POST',
                        dataType: 'json',
                        data: {attribute_id: ui.item.id, template_id: templateId, group: $(this).data('group')},
                        showLoader: true
                    }).done(function() {
                        setTimeout(function() { //do deferred
                            $('[data-form=edit-product]').trigger('changeAttributeSet', {id: templateId});
                        }, 10);
                    });
                }
        });
    });
script;
?>
    <?= /* @noEscape */ $secureRenderer->renderTag('script', [], $scriptString, false) ?>
</div>
