$(document).on('click', '.selectTrigger', function (e) {
    e.stopPropagation();
    $(this).closest('.customSelect').toggleClass('open');
});

$(document).on('click', '.selectOptions li', function (e) {
    e.stopPropagation();
    const $item       = $(this);
    const $container  = $item.closest('.customSelect');
    const val         = $item.data('value');
    const text        = $item.text();
    const $input      = $container.find('.selectValue');
    const $label      = $container.find('.selectLabel');
    const $allOptions = $container.find('.selectOptions li');

    $allOptions.removeClass('selected');

    $item.addClass('selected');

    $input.val(val);
    $label.text(text);
    $input.trigger('change');
    $label.removeClass('placeholder');
    $container.removeClass('open');
});

/* ── Multi-select trigger ─────────────────── */
$(document).on('click', '.selectTriggerBulk', function (e) {
    e.stopPropagation();
    $(this).closest('.customSelect').toggleClass('open');
});


$(document).on('click', '.selectOptionsBulk li', function (e) {
    e.stopPropagation();
    const $item      = $(this);
    const $container = $item.closest('.customSelect');
    const val        = $item.data('value');
    const text       = $item.text();
    const $label     = $container.find('.selectLabel');
    const $input     = $container.find('.selectValue');

    let inputArr    =  $input.val() ? JSON.parse($input.val()) : [];
    let containerArr = Array.isArray($container.data('value')) ? $container.data('value') : [];

    if ($item.hasClass('selected')) {
        $item.removeClass('selected');
        inputArr    = inputArr.filter(i => i !== val);
        containerArr = containerArr.filter(i => i !== text);
    } else {
        $item.addClass('selected');
        inputArr.push(val);
        containerArr.push(text);
    }

    $container.data('value', containerArr);
    $input.val(JSON.stringify(inputArr));

    $input.trigger('change');

    if (containerArr.length > 0) {
        $label.removeClass('placeholder').text(containerArr.join(', '));
    } else {
        $label.addClass('placeholder').text('Bitte auswählen…');
    }

});

$(document).on('click', () => $('.customSelect').removeClass('open'));