{% if favoriteExercises %}
<div id="favoriteExercises-{{ blockId }}" data-select-mode="{{ selectMode }}" {% if selectMode != 'none' and formId %}data-form-id="{{ formId }}"{% endif %}>
    {% if selectMode == 'none' %}
    <ul class="animated_list pl-0">
        {% for exercise in favoriteExercises %}
        <li class="w-100 favoriteExerciseItem">
        <i class="fas fa-link mr-3"></i><a class="text-color-black" href="{{exercise.getUrl()}}">{{exercise.getTitle()}}</a>
        </li>
        {% endfor %}
    </ul>
    {% elseif selectMode == 'single' %}
    <ul class="animated_list pl-0">
        {% for exercise in favoriteExercises %}
        <li class="w-100 favoriteExerciseItem d-flex align-items-center">
            <div class="form-check m-0 d-flex align-items-center">
                <input class="form-check-input favex-input" type="radio" name="favex-{{ blockId }}" value="{{ exercise.getUrl() }}" id="favex-{{ blockId }}-{{ loop.index }}" data-url="{{ exercise.getUrl() }}" data-exid="{{ exercise.getExercise_id() }}">
                <label class="form-check-label text-color-black mb-0 d-flex align-items-center" for="favex-{{ blockId }}-{{ loop.index }}">
                    <span>{{ exercise.getTitle() }}</span>
                    {% if urlButton %}
                    <a href="{{ exercise.getUrl() }}" target="_blank" rel="noopener" class="ml-2 favex-link text-color-black" style="-webkit-animation:none;-moz-animation:none;animation:none" aria-label="Übung öffnen">
                        <i class="fas fa-external-link-alt" style="-webkit-animation:none;-moz-animation:none;animation:none"></i>
                    </a>
                    {% endif %}
                </label>
            </div>
        </li>
        {% endfor %}
    </ul>
    {% elseif selectMode == 'multiple' %}
    <ul class="animated_list pl-0">
        {% for exercise in favoriteExercises %}
        <li class="w-100 favoriteExerciseItem d-flex align-items-center">
            <div class="form-check m-0 d-flex align-items-center">
                <input class="form-check-input favex-input" type="checkbox" name="favex-{{ blockId }}[]" value="{{ exercise.getUrl() }}" id="favex-{{ blockId }}-{{ loop.index }}" data-url="{{ exercise.getUrl() }}" data-exid="{{ exercise.getExercise_id() }}">
                <label class="form-check-label text-color-black mb-0 d-flex align-items-center" for="favex-{{ blockId }}-{{ loop.index }}">
                    <span>{{ exercise.getTitle() }}</span>
                    {% if urlButton %}
                    <a href="{{ exercise.getUrl() }}" target="_blank" rel="noopener" class="ml-2 favex-link text-color-black" style="-webkit-animation:none;-moz-animation:none;animation:none" aria-label="Übung öffnen">
                        <i class="fas fa-external-link-alt" style="-webkit-animation:none;-moz-animation:none;animation:none"></i>
                    </a>
                    {% endif %}
                </label>
            </div>
        </li>
        {% endfor %}
    </ul>
    {% endif %}
</div>

{% if formHtml %}
<div class="d-none" aria-hidden="true">
    {{ formHtml|raw }}
    <style>.d-none{display:none !important;}</style>
    <script>(function($){ $(function(){ $('.ts-forms-form-{{ formId }}').addClass('d-none'); }); })(jQuery);</script>
</div>
{% endif %}

{% if selectMode != 'none' %}
<script>
(function($){
    $(function(){
        var $container = $('#favoriteExercises-{{ blockId }}');
        var selectMode = ($container.data('select-mode') || 'none');
        var formId = $container.data('form-id') || null;

        function writeToForm(val){
            if(!formId) return;
            var $form = $('.ts-forms-form-' + formId);
            if($form.length === 0) return;
            var $target = $form.find('input.ts-forms-element[type="text"]').first();
            if($target.length === 0){ $target = $form.find('input[type="text"]').first(); }
            if($target.length === 0) return;
            $target.val(val).trigger('change');
        }

        function readFromForm(){
            if(!formId) return [];
            var $form = $('.ts-forms-form-' + formId);
            if($form.length === 0) return [];
            var $target = $form.find('input.ts-forms-element[type="text"]').first();
            if($target.length === 0){ $target = $form.find('input[type="text"]').first(); }
            if($target.length === 0) return [];
            var raw = ($target.val() || '').trim();
            if(!raw) return [];
            // Ergebnis: Array von exerciseIds (Zahlen oder Strings)
            var ids = [];
            // JSON-Array
            if(raw[0] === '[' && raw[raw.length-1] === ']'){
                try {
                    var arr = JSON.parse(raw);
                    if(Array.isArray(arr)){
                        for(var i=0;i<arr.length;i++){
                            var it = arr[i];
                            if(typeof it === 'number'){
                                ids.push(it);
                            } else if(typeof it === 'string'){
                                var s = it.trim();
                                if(s !== '' && !isNaN(s)) ids.push(parseInt(s,10));
                            } else if(it && (it.exerciseId != null)) {
                                ids.push(it.exerciseId);
                            }
                        }
                    }
                } catch(e) {}
            }
            // JSON-Objekt (alter Single-Format)
            if(ids.length === 0 && raw[0] === '{' && raw[raw.length-1] === '}'){
                try {
                    var obj = JSON.parse(raw);
                    if(obj && obj.exerciseId != null){ ids = [obj.exerciseId]; }
                } catch(e) {}
            }
            // Nur Zahl als String
            if(ids.length === 0 && !isNaN(raw)){
                ids = [parseInt(raw,10)];
            }
            // Separator-getrennte Zahlen
            if(ids.length === 0){
                var sep = null;
                if(raw.indexOf('\n') !== -1) sep = '\n';
                else if(raw.indexOf(';') !== -1) sep = ';';
                else if(raw.indexOf(',') !== -1) sep = ',';
                var parts = sep ? raw.split(sep) : [raw];
                for(var j=0;j<parts.length;j++){
                    var p = (parts[j] || '').trim();
                    if(p !== '' && !isNaN(p)) ids.push(parseInt(p,10));
                }
            }
            // Duplikate entfernen
            var seen = {}; var uniq = [];
            for(var k=0;k<ids.length;k++){
                var key = '' + ids[k];
                if(!seen[key]){ seen[key] = 1; uniq.push(ids[k]); }
            }
            return uniq;
        }
        $container.on('change', 'input.favex-input', function(){
            if(selectMode === 'single'){
                var $sel = $container.find('input.favex-input:checked').first();
                var id = $sel.data('exid');
                writeToForm((id != null ? '["' + String(id) + '"]' : ''));
            } else if(selectMode === 'multiple') {
                var arr = [];
                $container.find('input.favex-input:checked').each(function(){
                    var id = $(this).data('exid');
                    if(id != null){ arr.push('"' + String(id) + '"'); }
                });
                writeToForm('[' + arr.join(',') + ']');
            }
        });

        // Vorbelegen aus Formularwert
        var initial = readFromForm();
        if(initial.length > 0){
            if(selectMode === 'single'){
                var wantId = initial[0];
                var $radio = $container.find('input.favex-input[type="radio"][data-exid="' + wantId + '"]');
                if($radio.length){ $radio.first().prop('checked', true).trigger('change'); }
            } else if(selectMode === 'multiple'){
                var used = {};
                var wantSet = {};
                for(var i=0;i<initial.length;i++){ wantSet[''+initial[i]] = 1; }
                $container.find('input.favex-input[type="checkbox"]').each(function(){
                    var id = $(this).data('exid');
                    var key = ''+id;
                    if(id != null && wantSet[key] && !used[key]){ $(this).prop('checked', true); used[key] = 1; }
                });
                $container.find('input.favex-input[type="checkbox"]').first().trigger('change');
            }
        }
    });
})(jQuery);
</script>
{% endif %}

{% else %}
    {% include "dashboard/no-dashboard-item.html" with {'heading': defaultErrorSubject} %}
{% endif %}