// /treatment_modal.js
// Script global para gestionar el modal de creación/edición de tratamientos.
// VERSIÓN SUPER-SIMPLIFICADA: SIN FILTROS (Solo búsqueda por texto)
// Es llamado por 'fitxa_pacient.php' y 'treatments.php'.

// (La función 'getCategoryFamilyIds' ha sido eliminada)

function initializeTreatmentModalApp(config) {
    // --- Configuración Global ---
    const {
        allFisios,
        // allCategories, // <--- ELIMINADO
        // allTags, // <--- ELIMINADO
        IS_SUPERADMIN,
        CURRENT_USER_ID,
        PATIENT_ID = null,
        PATIENT_FULLNAME = null,
        onSaveSuccess = null
    } = config;

    // --- Instancias de Modales ---
    const treatmentModal = new bootstrap.Modal('#treatmentModal');
    const selectProtocolModal = new bootstrap.Modal('#selectProtocolModal');
    const manageModal = new bootstrap.Modal('#manageModal');
    const exerciseChangeConfirmationModal = new bootstrap.Modal('#exercise-change-confirmation-modal');

    // --- Variables de Estado del Modal ---
    // (modalCategoryFilter y modalTagsFilter eliminados)
    let fisioTomSelect;
    let dateRangePicker;
    let cardToRemove = null;
    let allProtocols = [];

    // --- Inicialización de componentes del Modal ---

    function initializeGlobalFormDependencies() {
        const pacienteSelectEl = document.getElementById('paciente_id_select');
        const fisioSelectEl = document.getElementById('assigned_fisios_select');

        if (pacienteSelectEl) {
            if (PATIENT_ID && PATIENT_FULLNAME) {
                $(pacienteSelectEl).html(`<option value="${PATIENT_ID}" selected>${PATIENT_FULLNAME}</option>`).prop('disabled', true);
            } else {
                $(pacienteSelectEl).prop('disabled', false);
            }
        }

        if (fisioSelectEl && typeof TomSelect !== 'undefined') {
            if (fisioTomSelect) fisioTomSelect.destroy();
            fisioTomSelect = new TomSelect(fisioSelectEl, { plugins: ['remove_button'], placeholder: 'Afig col·laboradors...' });
        }

        const datePickerEl = document.getElementById('date_range_picker');
        if (datePickerEl && typeof flatpickr !== 'undefined') {
            const options = {
                mode: 'range',
                dateFormat: "Y-m-d",
                locale: "es",
                altInput: true,
                altFormat: "d F, Y",
                onChange: function(selectedDates, dateStr, instance) {
                    if (selectedDates.length > 0) {
                        const todayStr = new Date().toISOString().split('T')[0];
                        const startDateStr = instance.formatDate(selectedDates[0], "Y-m-d");

                        if (startDateStr > todayStr) {
                            $('#delivery_programmed').prop('checked', true);
                        } else {
                            $('#delivery_immediate').prop('checked', true);
                        }
                    }

                    if (selectedDates.length === 2) {
                        $('#start_date_hidden').val(instance.formatDate(selectedDates[0], "Y-m-d"));
                        $('#end_date_hidden').val(instance.formatDate(selectedDates[1], "Y-m-d"));
                    } else {
                        $('#start_date_hidden').val('');
                        $('#end_date_hidden').val('');
                    }
                }
            };
            dateRangePicker = flatpickr(datePickerEl, options);
        }
    }

    // <--- ELIMINADA: La función 'initializeModalFilters' ya no es necesaria

    // --- Lógica de la Biblioteca de Ejercicios ---

    function loadModalExerciseLibrary() {

        const params = {
            ajax: true,
            action: 'get_rich_exercise_library',
            search: $('#exerciseSearchInput').val(),
            filterMine: $('#filterMyExercisesModalTreatment').is(':checked'),
            category: [], // <--- ELIMINADO: Siempre enviamos array vacío
            tags: [] // <--- ELIMINADO: Siempre enviamos array vacío
        };

        $('#exercise-library-container').html('<div class="text-center p-3"><div class="spinner-border spinner-border-sm"></div></div>');

        $.getJSON('exercises.php', params, response => {
            if (response.status === 'success') renderLibrary(response.exercises);
            else { $('#exercise-library-container').html('<div class="alert alert-warning">Error carregant exercicis.</div>'); }
        }).fail(() => {
            $('#exercise-library-container').html('<div class="alert alert-danger">Error de connexió.</div>');
        });
    }

    function renderLibrary(exercises) {
            const container = $('#exercise-library-container').empty();
            if (exercises.length === 0) {
                container.html('<div class="text-muted text-center p-3">No s\'han trobat exercicis.</div>');
                return;
            }

            const assignedIds = new Set();
            $('#assigned-exercises-container .assigned-exercise-card').each(function() {
                assignedIds.add($(this).data('id'));
            });

            exercises.forEach(ex => {
                let thumbnailHtml;
                if (ex.video_filename) {
                    const isEmbed = ex.video_filename.startsWith('http');

                    if (isEmbed) {
                        const ytMatch = ex.video_filename.match(/youtube\.com\/embed\/([a-zA-Z0-9\-_]+)/);
                        if (ytMatch) {
                            // YouTube -> Imagen
                            thumbnailHtml = `<img src="https://img.youtube.com/vi/${ytMatch[1]}/mqdefault.jpg" class="protocol-exercise-library-thumb">`;
                        } else {
                            // ★ CORRECCIÓN: Video Externo (MP4) -> Video Tag
                            thumbnailHtml = `<video src="${ex.video_filename}#t=0.5" class="protocol-exercise-library-thumb" muted playsinline></video>`;
                        }
                    } else {
                        // Video Local -> Video Tag
                        thumbnailHtml = `<video src="videos/${ex.video_filename}#t=0.5" class="protocol-exercise-library-thumb" muted playsinline></video>`;
                    }
                } else if (ex.image_filename) {
                    thumbnailHtml = `<img src="images/${ex.image_filename}" class="protocol-exercise-library-thumb">`;
                } else {
                    thumbnailHtml = `<div class="protocol-exercise-library-thumb d-flex flex-column align-items-center justify-content-center bg-light border text-muted"><i class="bi bi-camera-video-off"></i><small style="font-size: 0.6em; line-height: 1; white-space: nowrap;">Sense medis</small></div>`;
                }

                const alreadyAdded = assignedIds.has(ex.id);
                const escapedExerciseData = JSON.stringify(ex).replace(/'/g, '&apos;').replace(/"/g, '&quot;');

                const itemHtml = `
                    <div class="list-group-item d-flex justify-content-between align-items-center">
                        <div class="d-flex align-items-center">${thumbnailHtml}<span class="ms-2 small">${escapeHtml(ex.title)}</span></div>
                        <button type="button" class="btn btn-sm btn-outline-primary add-exercise-btn" ${alreadyAdded ? 'disabled' : ''} data-exercise-id="${ex.id}" data-exercise='${escapedExerciseData}'>
                            <i class="bi ${alreadyAdded ? 'bi-check-lg' : 'bi-plus-lg'}"></i>
                        </button>
                    </div>`;
                container.append(itemHtml);
            });
        }

    function checkAssignedPlaceholder(show) {
        const container = $('#assigned-exercises-container');
        const placeholderId = 'placeholder-assigned';
        if (show && container.children('.assigned-exercise-card').length === 0) {
            container.html(`<div id="${placeholderId}" class="text-muted text-center p-5 d-flex align-items-center justify-content-center h-100"><div><i class="bi bi-arrow-left-short fs-1"></i><br>Afig exercicis des de la biblioteca</div></div>`);
        } else if (!show) {
            $(`#${placeholderId}`).remove();
        }
    }

    function addExerciseToDOM(exerciseData, fromDB = false) {
        if (typeof exerciseData === 'string') {
            try {
                exerciseData = JSON.parse(exerciseData.replace(/&apos;/g, "'").replace(/&quot;/g, '"'));
            } catch(e) { console.error("Error parsing exercise data:", e, exerciseData); return; }
        }
        if (!exerciseData || $(`#assigned-exercises-container .assigned-exercise-card[data-id="${exerciseData.id}"]`).length > 0) return;

        checkAssignedPlaceholder(false);
        const noMediaBadge = (!exerciseData.video_filename && !exerciseData.image_filename) ? '<span class="badge bg-light text-dark fw-normal ms-2">Sense medis</span>' : '';

        const assignedHtml = $(`
            <div class="card card-body p-2 mb-2 assigned-exercise-card" data-id="${exerciseData.id}">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <div class="d-flex align-items-center">
                        <i class="bi bi-grip-vertical drag-handle me-2"></i>
                        <strong class="text-primary">${escapeHtml(exerciseData.title)}</strong>
                        ${noMediaBadge}
                    </div>
                    <button type="button" class="btn-close remove-exercise-btn"></button>
                </div>
                <div class="row gx-2">
                    <div class="col-4"><select class="form-select form-select-sm" data-field="frecuencia"><option>Diari</option><option>Altern</option><option>3xSetmana</option><option>2xSetmana</option></select></div>
                    <div class="col"><div class="input-group input-group-sm"><span class="input-group-text"><i class="bi bi-arrow-repeat"></i></span><input type="text" class="form-control" placeholder="Sèries" data-field="series" value="${escapeHtml(exerciseData.series || '')}"></div></div>
                    <div class="col"><div class="input-group input-group-sm"><span class="input-group-text"><i class="bi bi-stopwatch"></i></span><input type="text" class="form-control" placeholder="Reps" data-field="repetitions" value="${escapeHtml(exerciseData.repetitions || '')}"></div></div>
                    <div class="col"><div class="input-group input-group-sm"><span class="input-group-text"><i class="bi bi-clock-history"></i></span><input type="text" class="form-control" placeholder="Descans" data-field="rest_time" value="${escapeHtml(exerciseData.rest_time || '')}"></div></div>
                </div>
                <textarea class="form-control form-control-sm mt-2" rows="1" placeholder="Notes específiques per a aquest tractament..." data-field="notes">${escapeHtml((fromDB ? exerciseData.pauta_notes : exerciseData.notes) || '')}</textarea>
            </div>`);

        assignedHtml.find('[data-field="frecuencia"]').val(fromDB ? (exerciseData.frecuencia || 'Diari') : (exerciseData.frecuencia || 'Diari'));
        $('#assigned-exercises-container').append(assignedHtml);

        if (!fromDB) {
            $(`#exercise-library-container .add-exercise-btn[data-exercise-id="${exerciseData.id}"]`).prop('disabled', true).html('<i class="bi bi-check-lg"></i>');
        }
    }

    function removeCardFromDOM(card) {
        const exerciseId = card.data('id');
        card.remove();
        if ($('#assigned-exercises-container .assigned-exercise-card').length === 0) {
            checkAssignedPlaceholder(true);
        }
        $(`#exercise-library-container .add-exercise-btn[data-exercise-id="${exerciseId}"]`).prop('disabled', false).html('<i class="bi bi-plus-lg"></i>');
    }

    // --- Lógica de Apertura de Modales ---

    function populateAndOpenModalCRUD(data = {}) {
        const form = $('#treatmentForm');
        form[0].reset();
        $('#treatmentModalLabel').text(data.id ? 'Editar Tractament' : 'Nou Tractament');
        $('#treatmentId').val(data.id || '');

        const pacienteSelect = $('#paciente_id_select');
        if (PATIENT_ID && PATIENT_FULLNAME) {
            pacienteSelect.html(`<option value="${PATIENT_ID}" selected>${PATIENT_FULLNAME}</option>`).prop('disabled', true);
            form.find('[name="paciente_id"]').val(PATIENT_ID);
        } else {
            pacienteSelect.prop('disabled', false);
            if(data.paciente_id) {
                pacienteSelect.val(data.paciente_id);
            }
        }

        if (fisioTomSelect) {
            fisioTomSelect.clear();
            const filteredFisios = allFisios.filter(f => f.id != CURRENT_USER_ID);
            fisioTomSelect.addOptions(filteredFisios.map(f => ({value: f.id, text: `${f.nombre} ${f.apellido}`})));

            let fisiosToSelect = [];
            if (data.id) {
                const creatorId = data.creator_fisio_id || null;
                const assignedIds = data.assigned_fisios || [];
                fisiosToSelect = assignedIds.filter(id => {
                    const isCreator = (id == creatorId);
                    const isCurrentUser = (id == CURRENT_USER_ID);
                    const fisio = allFisios.find(f => f.id == id);
                    const isSuperadmin = fisio && fisio.rol === 'superadmin';
                    return !isCreator && !isCurrentUser;
                });
            }
            fisioTomSelect.setValue(fisiosToSelect);
        }

        if(data.id) { // Editando
            form.find('[name="title"]').val(data.title);
            form.find('[name="anamnesis"]').val(data.anamnesis);
            form.find('[name="diagnostico"]').val(data.diagnostico);
            if (dateRangePicker) dateRangePicker.setDate([data.start_date, data.end_date], true);
            $('#start_date_hidden').val(data.start_date || '');
            $('#end_date_hidden').val(data.end_date || '');
            const isProgrammed = data.status === 'Programat';
            $('#delivery_programmed').prop('checked', isProgrammed);
            $('#delivery_immediate').prop('checked', !isProgrammed);
        } else { // Creando
            form.find('[name="title"]').val(data.title || '');
            form.find('[name="anamnesis"]').val(data.anamnesis || '');
            form.find('[name="diagnostico"]').val(data.diagnostico || '');
            if (dateRangePicker) dateRangePicker.clear();
            $('#start_date_hidden').val('');
            $('#end_date_hidden').val('');
            $('#delivery_immediate').prop('checked', true);
            setTimeout(() => {
                $('#delivery_immediate').trigger('change');
            }, 100);
        }

        if (fisioTomSelect) {
            fisioTomSelect.enable();
            if (data.id) {
                const isCreatorOrAdmin = IS_SUPERADMIN || data.creator_fisio_id == CURRENT_USER_ID;
                if (!isCreatorOrAdmin) fisioTomSelect.disable();
            }
        }

        $('#assigned-exercises-container').empty();
        if (data.assigned_exercises && data.assigned_exercises.length > 0) {
            checkAssignedPlaceholder(false);
            data.assigned_exercises.forEach(ex => addExerciseToDOM(ex, true));
        } else {
            checkAssignedPlaceholder(true);
        }

        // =======================================================
        // ============ INICIO: MODIFICACIÓN JS (X) ============
        // =======================================================
        $('#exerciseSearchInput').val('');
        $('#clearModalSearchBtn').hide(); // <-- AÑADIDO
        $('#filterMyExercisesModalTreatment').prop('checked', false);
        loadModalExerciseLibrary();
        // =======================================================
        // ============= FIN: MODIFICACIÓN JS (X) ============
        // =======================================================

        const container = document.getElementById('assigned-exercises-container');
        if (typeof Sortable !== 'undefined') {
            if (container.sortableInstance) container.sortableInstance.destroy();
            container.sortableInstance = new Sortable(container, { animation: 150, handle: '.drag-handle', ghostClass: 'sortable-ghost' });
        }
        treatmentModal.show();
    }

    function loadProtocolsForModal() {
        const searchTerm = $('#protocolSearchInputModal').val();
        const container = $('#protocol-list-modal-container');
        container.html('<div class="text-center p-3"><div class="spinner-border spinner-border-sm"></div></div>');

        if (searchTerm === '' && allProtocols.length > 0) {
            renderProtocolsForModal(allProtocols);
            return;
        }

        $.getJSON('protocols.php', { ajax: true, action: 'read_protocols', search: searchTerm, page: 1, limit: 50 })
            .done(response => {
                if (response.status === 'success') {
                    if (searchTerm === '') {
                        allProtocols = response.protocols || [];
                    }
                    renderProtocolsForModal(response.protocols);
                } else {
                    container.html('<div class="text-muted text-center p-3">No s\'han trobat protocols.</div>');
                }
            })
            .fail(() => container.html('<div class="alert alert-danger">Error carregant protocols.</div>'));
    }

    function renderProtocolsForModal(protocols) {
            const container = $('#protocol-list-modal-container');
            container.empty();
            if (protocols.length === 0) {
                container.html('<div class="text-muted text-center p-3">No s\'han trobat protocols.</div>');
                return;
            }

            protocols.forEach(p => {
                let thumbnailHtml = `<div class="protocol-modal-thumbnail no-media-placeholder d-flex align-items-center justify-content-center"><i class="bi bi-camera-video-off"></i></div>`;
                let creatorInfo = `Creat per: ${escapeHtml(p.creator_name)} ${escapeHtml(p.creator_surname)}`;

                if (p.first_video_filename) {
                    if (p.first_video_filename.startsWith('http')) {
                        const ytMatch = p.first_video_filename.match(/youtube\.com\/embed\/([a-zA-Z0-9\-_]+)/);
                        if (ytMatch) {
                            // YouTube
                            thumbnailHtml = `<img src="https://img.youtube.com/vi/${ytMatch[1]}/mqdefault.jpg" class="protocol-modal-thumbnail" alt="Miniatura">`;
                        } else {
                            // ★ CORRECCIÓN: Video Externo (MP4)
                            thumbnailHtml = `<video src="${p.first_video_filename}#t=0.5" class="protocol-modal-thumbnail" preload="metadata"></video>`;
                        }
                    } else {
                        // Local
                        thumbnailHtml = `<video src="videos/${p.first_video_filename}#t=0.5" class="protocol-modal-thumbnail" preload="metadata"></video>`;
                    }
                } else if (p.first_image_filename) {
                    thumbnailHtml = `<img src="images/${p.first_image_filename}" class="protocol-modal-thumbnail" alt="Miniatura">`;
                }

                const itemHtml = `
                    <div class="list-group-item list-group-item-action select-protocol-item" data-id="${p.id}" style="cursor: pointer;">
                        <div class="protocol-modal-item">
                            ${thumbnailHtml}
                            <div class="protocol-modal-info">
                                <p class="protocol-modal-title" title="${escapeHtml(p.title)}">${escapeHtml(p.title)}</p>
                                <p class="protocol-modal-subtitle">${creatorInfo}</p>
                            </div>
                            <span class="badge bg-secondary rounded-pill ms-3 flex-shrink-0">${p.exercise_count} ex.</span>
                        </div>
                    </div>`;
                container.append(itemHtml);
            });
        }

    // --- Handlers de Eventos Globales ---

    $(document).on('click', '#addTreatmentBtn', () => {
        populateAndOpenModalCRUD(PATIENT_ID ? { paciente_id: PATIENT_ID } : {});
    });

    $(document).on('click', '.edit-treatment-btn', function(e) {
        e.preventDefault();
        if ($(this).hasClass('disabled')) return;
        const treatmentId = $(this).data('id');

        $.getJSON('treatments.php', { ajax: true, action: 'get_treatment_details', id: treatmentId })
            .done(response => {
                if (response.status === 'success') {
                    populateAndOpenModalCRUD(response.treatment);
                } else { showToast(response.message || 'Error en carregar dades.', 'danger'); }
            })
            .fail(xhr => showToast(xhr.responseJSON?.message || 'Error de connexió.', 'danger'));
    });

    $(document).on('click', '#assignProtocolBtn', function() {
        $('#protocolSearchInputModal').val('');
        loadProtocolsForModal();
        selectProtocolModal.show();
    });

    $(document).on('click', '.select-protocol-item', function() {
        const protocolId = $(this).data('id');
        selectProtocolModal.hide();

        $.getJSON('patient_ajax.php', {
            ajax: true,
            action: 'get_protocol_details_for_assignment',
            protocol_id: protocolId,
            pacient_id: PATIENT_ID
        })
        .done(response => {
            if (response.status === 'success') {
                const protocolData = response.protocol;
                populateAndOpenModalCRUD({
                    title: `(Protocol) ${protocolData.title}`,
                    anamnesis: protocolData.anamnesis,
                    diagnostico: protocolData.diagnostico,
                    paciente_id: PATIENT_ID,
                    assigned_exercises: protocolData.assigned_exercises,
                    start_date: null,
                    end_date: null,
                    assigned_fisios: [CURRENT_USER_ID]
                });
            } else { showToast(response.message || 'Error carregant detalls.', 'danger'); }
        })
        .fail(xhr => showToast(xhr.responseJSON?.message || 'Error de connexió.', 'danger'));
    });

    $(document).on('click', '.add-exercise-btn', function() { addExerciseToDOM($(this).data('exercise')); });
    $(document).on('click', '.remove-exercise-btn', function() {
        const card = $(this).closest('.assigned-exercise-card');
        const exerciseId = card.data('id');
        const treatmentId = $('#treatmentId').val();

        if (!treatmentId) {
            removeCardFromDOM(card);
            return;
        }

        $.post('treatments.php', {
            ajax: true,
            action: 'check_single_exercise_data_loss',
            treatment_id: treatmentId,
            exercise_id: exerciseId
        }, 'json')
        .done(response => {
            if (response.has_data) {
                cardToRemove = card;
                const exerciseTitle = card.find('strong').text();
                $('#exercises-to-delete-list').empty().append(`<li class="list-group-item"><strong>${escapeHtml(exerciseTitle)}</strong></li>`);
                exerciseChangeConfirmationModal.show();
            } else {
                removeCardFromDOM(card);
            }
        }).fail(() => showToast('Error en comprovar dades d\'evolució.', 'danger'));
    });

    $('#confirm-exercise-delete-btn').on('click', function() {
        if (cardToRemove) {
            removeCardFromDOM(cardToRemove);
            cardToRemove = null;
        }
        exerciseChangeConfirmationModal.hide();
    });

    $('#treatmentForm').on('submit', function(e) {
        e.preventDefault();

        const $submitBtn = $(this).find('button[type="submit"]');
        const originalBtnText = $submitBtn.html();
        $submitBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Guardant...');

        const action = $('#treatmentId').val() ? 'update_treatment' : 'create_treatment';
        if (!dateRangePicker || !dateRangePicker.selectedDates || dateRangePicker.selectedDates.length < 2) {
            showToast('Has de seleccionar un rang de dates.', 'danger');
            $submitBtn.prop('disabled', false).html(originalBtnText);
            return;
        }

        let assignedExercises = [];
        $('#assigned-exercises-container .assigned-exercise-card').each(function() {
            assignedExercises.push({
                id: $(this).data('id'),
                frecuencia: $(this).find('[data-field="frecuencia"]').val() || 'Diari',
                series: $(this).find('[data-field="series"]').val() || '',
                repetitions: $(this).find('[data-field="repetitions"]').val() || '',
                rest_time: $(this).find('[data-field="rest_time"]').val() || '',
                notes: $(this).find('[data-field="notes"]').val() || ''
            });
        });
        $('#assignedExercisesInput').val(JSON.stringify(assignedExercises));

        if (assignedExercises.length === 0) {
            showToast('Has de seleccionar almenys un exercici.', 'danger');
            $submitBtn.prop('disabled', false).html(originalBtnText);
            return;
        }

        const formData = $(this).serialize();

        $.post('treatments.php', `ajax=true&action=${action}&${formData}`, 'json')
            .done(response => {
                if (response.status === 'success') {
                    showToast(response.message, 'success');
                    treatmentModal.hide();

                    if (response.new_treatment_id && action === 'create_treatment') {
                        $.post('treatments.php', {
                            ajax: true,
                            action: 'send_treatment_notification',
                            treatment_id: response.new_treatment_id,
                            type: 'new_treatment'
                        }).fail(err => console.error('Error email', err));
                    }

                    if (response.reassigned_treatment_id && action === 'update_treatment') {
                        $.post('treatments.php', {
                            ajax: true,
                            action: 'send_treatment_notification',
                            treatment_id: response.reassigned_treatment_id,
                            type: 'reassign'
                        }).fail(err => console.error('Error email', err));
                    }

                    if (typeof onSaveSuccess === 'function') {
                        let idToHighlight = null;
                        if (action === 'create_treatment' && response.new_treatment_id) idToHighlight = response.new_treatment_id;
                        else if (action === 'update_treatment') idToHighlight = $('#treatmentId').val();
                        onSaveSuccess(idToHighlight);
                    } else {
                        if (typeof loadPatientTreatments === 'function') loadPatientTreatments();
                        if (typeof fetchTreatments === 'function') fetchTreatments();
                    }

                } else {
                    showToast(response.message || 'Error al guardar.', 'danger');
                }
            })
            .fail(xhr => {
                console.error("Submit Error:", xhr.responseText);
                showToast(xhr.responseJSON?.message || 'Error en guardar.', 'danger');
            })
            .always(() => {
                $submitBtn.prop('disabled', false).html(originalBtnText);
            });
    });

    // Handlers para sincronizar botones de radio y calendario
    function getCurrentEndDate() {
        return (dateRangePicker && dateRangePicker.selectedDates.length === 2) ? dateRangePicker.selectedDates[1] : null;
    }

    $(document).on('change', 'input[name="delivery_option"]', function() {
        if (!dateRangePicker) return;
        const today = new Date();
        const tomorrow = new Date();
        tomorrow.setDate(today.getDate() + 1);

        let currentEndDate = getCurrentEndDate();
        let newStartDate;

        if ($(this).val() === 'immediata' && $(this).is(':checked')) {
            newStartDate = today;
        } else if ($(this).val() === 'programada' && $(this).is(':checked')) {
            const currentStartDate = (dateRangePicker.selectedDates.length > 0) ? dateRangePicker.selectedDates[0] : null;
            if (currentStartDate && currentStartDate > today) newStartDate = currentStartDate;
            else newStartDate = tomorrow;
        } else return;

        if (!currentEndDate || currentEndDate < newStartDate) {
            currentEndDate = new Date(newStartDate);
            currentEndDate.setDate(currentEndDate.getDate() + 30);
        }
        dateRangePicker.setDate([newStartDate, currentEndDate], true);
    });


    // =======================================================
    // ============ INICIO: MODIFICACIÓN JS (X) ============
    // =======================================================

    // Handlers de los filtros de la biblioteca de ejercicios
    let protocolSearchTimeout;
    $('#protocolSearchInputModal').on('keyup', function() {
        clearTimeout(protocolSearchTimeout);
        protocolSearchTimeout = setTimeout(loadProtocolsForModal, 300);
    });

    // --- BLOQUE REEMPLAZADO ---
    let exerciseSearchTimeout;
    $('#exerciseSearchInput').on('keyup', function() {
        // Lógica para mostrar/ocultar la 'X'
        const hasText = $(this).val().length > 0;
        $('#clearModalSearchBtn').toggle(hasText);

        // Lógica de búsqueda (debounce)
        clearTimeout(exerciseSearchTimeout);
        exerciseSearchTimeout = setTimeout(loadModalExerciseLibrary, 300);
    });
    // --- FIN BLOQUE REEMPLAZADO ---

    $('#clearModalSearchBtn').on('click', () => $('#exerciseSearchInput').val('').trigger('keyup').focus());
    $('#filterMyExercisesModalTreatment').on('change', loadModalExerciseLibrary);

    // =======================================================
    // ============= FIN: MODIFICACIÓN JS (X) ============
    // =======================================================


    initializeGlobalFormDependencies();
    // <--- ELIMINADA: La llamada a 'initializeModalFilters'

    return { populateAndOpenModalCRUD };
}
