export function createDropdown(config) {
    const settings = {
        root: '[data-dropdown]',
        toggle: '[data-dropdown-toggle]',
        value: '[data-dropdown-value]',
        option: '[data-dropdown-option]',
        openClass: 'dropdown--open',
        selectedClass: 'dropdown__option--selected',
        selectedValueData: 'selected-value',
        ariaExpandedAttr: 'aria-expanded',
        ariaSelectedAttr: 'aria-selected',
        namespace: 'customDropdown',
        onSelect: function () {},
        ...config,
    };

    function closeAll() {
        $(settings.root).each(function () {
            const $dropdown = $(this);
            const $toggle = $dropdown.find(settings.toggle);

            $dropdown.removeClass(settings.openClass);
            $toggle.attr(settings.ariaExpandedAttr, 'false');
        });
    }

    function selectOption($dropdown, $option) {
        const $value = $dropdown.find(settings.value);
        const $options = $dropdown.find(settings.option);
        const selectedValue = $option.attr('data-value') || '';

        $options.removeClass(settings.selectedClass).attr(settings.ariaSelectedAttr, 'false');
        $option.addClass(settings.selectedClass).attr(settings.ariaSelectedAttr, 'true');

        if ($value.length) {
            $value.text($option.text().trim());
        }

        $dropdown.data(settings.selectedValueData, selectedValue);

        settings.onSelect($dropdown, $option, selectedValue);
    }

    function bind() {
        $(document).off(`click.${settings.namespace}`);
        $(document).on(`click.${settings.namespace}`, function (event) {
            const $target = $(event.target);
            const $toggle = $target.closest(settings.toggle);
            const $option = $target.closest(settings.option);
            const $dropdown = $target.closest(settings.root);

            if (!$dropdown.length) {
                closeAll();
                return;
            }

            if ($toggle.length) {
                const isOpen = $dropdown.hasClass(settings.openClass);

                closeAll();

                $dropdown.toggleClass(settings.openClass, !isOpen);
                $toggle.attr(settings.ariaExpandedAttr, String(!isOpen));

                return;
            }

            if ($option.length) {
                selectOption($dropdown, $option);
                closeAll();
            }
        });
    }

    return {
        bind,
        closeAll,
        selectOption,
    };
}
