<?php
/**
 * Copyright 2014 Adobe
 * All Rights Reserved.
 */

/**
 * @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer
 * @var \Magento\Framework\Escaper $escaper
 */
?>

<?php $_divId = 'tree' . $block->getId() ?>
<div id="<?= $escaper->escapeHtmlAttr($_divId) ?>" class="tree"></div>
<?php
$isUseMassAction = $block->getUseMassaction() ? 1 : 0;
$isAnchorOnly = $block->getIsAnchorOnly() ? 1 : 0;

$scriptString = <<<script

require(['jquery', 'jquery/jstree/jquery.jstree'], function($) {

    const tree = $('#tree{$block->escapeJs($block->getId())}');
    const useMassAction = {$isUseMassAction};
    const isAnchorOnly = {$isAnchorOnly};
    let checkedNodes = [];
    let anchorNodes = [];
    let nonAnchorNodes = [];

    function actionBasedOnIsAnchorOnly() {
        if (isAnchorOnly) {
            tree.jstree(true).disable_node(nonAnchorNodes);
        } else {
            tree.jstree(true).disable_node(anchorNodes);
        }
    }

    function handleLoadedNode(e, data) {
        const container = $(e.target).closest('div.chooser_container');
        if (container.find('input[type="text"].entities').val() !== '') {
            checkedNodes = container.find('input[type="text"].entities').val().split(',').map(item => item.trim());
        }

        if (data.status) {
            tree.jstree(true).select_node(checkedNodes);
            actionBasedOnIsAnchorOnly();
        }
    }

    function handleChange(e, data) {
        if (data.action === 'ready') {
            return;
        }

        if (useMassAction) {
            const clickedNodeID = data.node.id;

            if (data.action === 'select_node' && !checkedNodes.includes(clickedNodeID)) {
                checkedNodes.push(clickedNodeID);
            } else if (data.action === 'deselect_node') {
                checkedNodes = checkedNodes.filter(nodeID => nodeID !== clickedNodeID);
            }

            checkedNodes.sort((a, b) => a - b);
            const container = $(e.target).closest('div.chooser_container');
            container.find('input[type="text"].entities').val(checkedNodes.join(','));
        } else {
            node = data.node;
            node.attributes = node.original;
            const nodeClickListener = {$block->getNodeClickListener()};
            nodeClickListener(node);
        }
    }

    function updateChildrenKey(treeJson) {
        treeJson.forEach(node => {
            if (Array.isArray(node.children) && node.children.length === 0) {
                node.children = true;
            } else if (Array.isArray(node.children)) {
                updateChildrenKey(node.children);
            }

            if (node.is_anchor === 1) {
                anchorNodes.push(node.id);
            } else {
                nonAnchorNodes.push(node.id);
            }
        });
        return treeJson;
    }

    var jstreeConfig = {
        core: {
            data: function (obj, callback) {
                if (obj.id != '#' && obj.children.length === 0) {
                    let data = {
                        id: obj.id,
                        store: obj.original.store,
                        node: obj.id,
                        form_key: FORM_KEY
                    };

                    $.ajax({
                        url: '{$block->escapeJs($block->getLoadTreeUrl())}',
                        type: "POST",
                        data: data,
                        dataType: 'json',
                        success: function (response) {
                            response = updateChildrenKey(response);
                            callback.call(this, response);
                        },
                        error: function (jqXHR, status, error) {
                            console.log(status + ': ' + error);
                        }
                    });
                } else {
                    let defaultTree = updateChildrenKey({$block->getTreeJson()});
                    callback.call(this, defaultTree);
                }
            },
            check_callback: true
        },
        plugins: ['dnd']
    };

    if (useMassAction) {
        jstreeConfig.plugins.push('checkbox');
        jstreeConfig.checkbox = {
            three_state: false
        };
    }

    tree.jstree(jstreeConfig);

    if (useMassAction) {
        tree.on('load_node.jstree', (e, data) => handleLoadedNode(e, data));
    }

    tree.on('changed.jstree', (e, data) => handleChange(e, data));
});

script;
?>
<?= /* @noEscape */ $secureRenderer->renderStyleAsTag(
    'overflow-x: auto;',
    '#tree' . $escaper->escapeJs($block->getId())
);
?>
<?= /* @noEscape */ $secureRenderer->renderTag('script', [], $scriptString, false); ?>
