import { onPageLoadComplete } from '@nimius/event-utility';
import { listenForAddedElements } from '@nimius/dom-utility';
import jsFeatureQuery from '../../Scripts/base/js-feature-query';
import { ItemFilter } from '../../Scripts/common/item-filter';
import { TportalShoppingcart } from '../../Scripts/tportal-shoppingcart';
import { TportalCountLink } from '../../Scripts/tportal-count-link';

/**
 * @returns {Promise<Function>}
 */
async function loadTargetEnhancement() {
    const { targetEnhance } = await import(/* webpackChunkName: "target-enhancement" */ '@nimius/target-enhancement');
    return targetEnhance;
}

onPageLoadComplete(() => {
    jsFeatureQuery();

    listenForAddedElements(
        { selector: '[data-target-enhancement]', checkForExistingNodes: true },
        element => loadTargetEnhancement().then(targetEnhance => targetEnhance(element))
    );

    for (const element of document.querySelectorAll('[data-item-filter]')) {
        new ItemFilter(element);
    }

    // Deprecated, is replaced by TportalCountLink class
    if (document.querySelector('[data-tportal-shoppingcart-count]')) {
        for (const element of document.querySelectorAll('[data-tportal-shoppingcart-count]')) {
            new TportalShoppingcart(element);

            console.warn(
                '## TportalShoppingcart Deprecation Notice \n[data-tportal-shoppingcart-count] Syntax will be replaced with a future version.\nPlease use [data-tportal-count-link] and the additional [data-tportal-count-type] instead.',
                element
            );
        }
    }

    // Replaces the deprecated TportalShoppingcart
    if (document.querySelector('[data-tportal-count-link]')) {
        for (const element of document.querySelectorAll('[data-tportal-count-link]')) {
            new TportalCountLink(element);
        }
    }
});
