<script>
    window.factoryCrudBoot = function factoryCrudBoot() {
        const ctx = window.factoryCrud;

        if (!ctx || ctx.booted) {
            return;
        }

        const modalElement = document.getElementById(ctx.selectors.modal);
        const form = document.getElementById(ctx.selectors.form);

        if (!modalElement || !form || typeof bootstrap === 'undefined') {
            return;
        }

        ctx.booted = true;
        ctx.modalElement = modalElement;
        ctx.form = form;
        ctx.modal = new bootstrap.Modal(modalElement, {
            backdrop: 'static',
        });
        ctx.methodInput = document.getElementById(ctx.selectors.methodInput);
        ctx.formModeInput = document.getElementById(ctx.selectors.formModeInput);
        ctx.updateUrlInput = document.getElementById(ctx.selectors.updateUrlInput);
        ctx.titleElement = document.getElementById(ctx.selectors.title);
        ctx.submitButton = document.getElementById(ctx.selectors.submitButton);
        ctx.returnEntityInput = document.getElementById(ctx.selectors.returnEntityInput);
        ctx.returnUrlInput = document.getElementById(ctx.selectors.returnUrlInput);
        ctx.restoreDraftKeyInput = document.getElementById(ctx.selectors.restoreDraftKeyInput);
        ctx.searchInput = document.getElementById(ctx.selectors.searchInput);
        ctx.searchForm = document.getElementById(ctx.selectors.searchForm);

        ctx.initializeTooltips = function initializeTooltips(scope = document) {
            scope.querySelectorAll('[data-bs-toggle="tooltip"]').forEach((element) => {
                bootstrap.Tooltip.getOrCreateInstance(element);
            });
        };

        ctx.setReturnFlowFields = function setReturnFlowFields({ returnEntity = '', returnUrl = '', restoreDraftKey = '' } = {}) {
            if (ctx.returnEntityInput) {
                ctx.returnEntityInput.value = returnEntity;
            }
            if (ctx.returnUrlInput) {
                ctx.returnUrlInput.value = returnUrl;
            }
            if (ctx.restoreDraftKeyInput) {
                ctx.restoreDraftKeyInput.value = restoreDraftKey;
            }
        };

        ctx.clearReturnFlowFields = function clearReturnFlowFields() {
            ctx.setReturnFlowFields();
        };

        ctx.clearValidationState = function clearValidationState() {
            ctx.form.querySelectorAll('.is-invalid').forEach((element) => element.classList.remove('is-invalid'));
            ctx.form.querySelectorAll('.invalid-feedback.d-block').forEach((element) => {
                if (!element.closest('.alert')) {
                    element.remove();
                }
            });
        };

        ctx.findReferenceOptionByCedula = function findReferenceOptionByCedula(datalistId, cedula) {
            const value = (cedula ?? '').toString().trim();
            if (!value) {
                return null;
            }

            const datalist = document.getElementById(datalistId);
            if (!datalist) {
                return null;
            }

            return Array.from(datalist.options).find((option) => (option.dataset.cedula || '').trim() === value) || null;
        };

        ctx.normalizeReferenceInputToCedula = function normalizeReferenceInputToCedula(displayInput, hiddenInput, datalistId) {
            if (!displayInput || !hiddenInput) {
                return;
            }

            const rawValue = displayInput.value.trim();
            if (!rawValue) {
                hiddenInput.value = '';
                return;
            }

            const datalist = document.getElementById(datalistId);
            if (!datalist) {
                hiddenInput.value = rawValue;
                return;
            }

            const matchedOption = Array.from(datalist.options).find((option) => option.value.trim().toLowerCase() === rawValue.toLowerCase())
                || Array.from(datalist.options).find((option) => (option.dataset.cedula || '').trim() === rawValue);

            hiddenInput.value = matchedOption?.dataset.cedula || rawValue;
            if (matchedOption) {
                displayInput.value = matchedOption.value;
            }
        };

        ctx.syncReferenceDisplayFromCedula = function syncReferenceDisplayFromCedula(hiddenInput, displayInput, datalistId) {
            if (!hiddenInput || !displayInput) {
                return;
            }

            const option = ctx.findReferenceOptionByCedula(datalistId, hiddenInput.value);
            displayInput.value = option ? option.value : hiddenInput.value || '';
        };

        ctx.setModalMode = function setModalMode({ mode = 'create', updateUrl = '' } = {}) {
            const isEditMode = mode === 'edit' && Boolean(updateUrl);
            ctx.form.action = isEditMode ? updateUrl : ctx.urls.store;
            if (ctx.formModeInput) {
                ctx.formModeInput.value = isEditMode ? 'edit' : 'create';
            }
            if (ctx.methodInput) {
                ctx.methodInput.value = isEditMode ? 'PUT' : 'POST';
            }
            if (ctx.updateUrlInput) {
                ctx.updateUrlInput.value = isEditMode ? updateUrl : '';
            }
            if (ctx.titleElement) {
                ctx.titleElement.textContent = isEditMode ? ctx.labels.editTitle : ctx.labels.createTitle;
            }
            if (ctx.submitButton) {
                ctx.submitButton.textContent = isEditMode ? ctx.labels.editSubmit : ctx.labels.createSubmit;
            }
            ctx.hooks.onSetModalMode.forEach((hook) => hook({ isEditMode, updateUrl, ctx }));
        };

        ctx.collectCurrentFormValues = function collectCurrentFormValues() {
            const formData = new FormData(ctx.form);
            const draft = {};
            for (const [key, value] of formData.entries()) {
                if (!key.startsWith('__') && !(value instanceof File)) {
                    draft[key] = value;
                }
            }
            return draft;
        };

        ctx.buildDraftStorageKey = function buildDraftStorageKey(draftKey) {
            return `${ctx.nestedDraftStoragePrefix}${draftKey}`;
        };

        ctx.readStoredDraft = function readStoredDraft(draftKey) {
            if (!draftKey) {
                return null;
            }
            try {
                const raw = window.sessionStorage.getItem(ctx.buildDraftStorageKey(draftKey));
                return raw ? JSON.parse(raw) : null;
            } catch (error) {
                return null;
            }
        };

        ctx.writeStoredDraft = function writeStoredDraft(draftKey, values) {
            if (!draftKey) {
                return;
            }
            try {
                window.sessionStorage.setItem(ctx.buildDraftStorageKey(draftKey), JSON.stringify(values));
            } catch (error) {
                return;
            }
        };

        ctx.clearStoredDraft = function clearStoredDraft(draftKey) {
            if (!draftKey) {
                return;
            }
            try {
                window.sessionStorage.removeItem(ctx.buildDraftStorageKey(draftKey));
            } catch (error) {
                return;
            }
        };

        ctx.cleanupFlowQueryParams = function cleanupFlowQueryParams(...paramNames) {
            const url = new URL(window.location.href);
            let hasChanges = false;
            paramNames.forEach((name) => {
                if (url.searchParams.has(name)) {
                    url.searchParams.delete(name);
                    hasChanges = true;
                }
            });
            if (hasChanges) {
                window.history.replaceState({}, document.title, `${url.pathname}${url.search}${url.hash}`);
            }
        };

        ctx.fillFormValues = function fillFormValues(record = {}, extras = {}) {
            Array.from(ctx.form.elements).forEach((element) => {
                if (
                    !element.name
                    || element.name.startsWith('__')
                    || element.name === '_token'
                    || element.name === '_method'
                    || element.type === 'file'
                ) {
                    return;
                }

                const value = Object.prototype.hasOwnProperty.call(record, element.name)
                    ? record[element.name]
                    : (ctx.defaultValues[element.name] ?? '');

                if (element.tagName === 'SELECT') {
                    element.value = value ?? '';
                    return;
                }

                if (element.type === 'checkbox') {
                    element.checked = value === true || value === '1' || value === 1;
                    return;
                }

                if (element.type === 'datetime-local' && value) {
                    const parsedDate = new Date(value);
                    if (!Number.isNaN(parsedDate.getTime())) {
                        const timezoneOffset = parsedDate.getTimezoneOffset() * 60000;
                        element.value = new Date(parsedDate.getTime() - timezoneOffset).toISOString().slice(0, 16);
                        return;
                    }
                }

                if (element.type === 'date' && value) {
                    element.value = String(value).slice(0, 10);
                    return;
                }

                if (element.type === 'password') {
                    element.value = '';
                    return;
                }

                element.value = value ?? '';
            });

            [
                ['modal_responsable', 'modal_responsable_display', 'modal_responsable_options'],
                ['modal_cedula_usuario', 'modal_cedula_usuario_display', 'modal_cedula_usuario_options'],
                ['modal_cedulaResponsable', 'modal_cedulaResponsable_display', 'modal_cedula_responsable_options'],
            ].forEach(([hiddenId, displayId, datalistId]) => {
                const hiddenInput = document.getElementById(hiddenId);
                const displayInput = document.getElementById(displayId);
                if (hiddenInput && displayInput) {
                    ctx.syncReferenceDisplayFromCedula(hiddenInput, displayInput, datalistId);
                }
            });

            ctx.hooks.onFillFormValues.forEach((hook) => hook({ record, extras, ctx }));
        };

        ctx.openCreateModal = function openCreateModal() {
            ctx.form.reset();
            ctx.clearValidationState();
            ctx.clearReturnFlowFields();
            ctx.setModalMode({ mode: 'create' });
            ctx.fillFormValues(ctx.defaultValues || {});
            ctx.modal.show();
        };

        ctx.openEditModal = function openEditModal(button) {
            const record = JSON.parse(button.dataset.record || '{}');
            const updateUrl = button.dataset.updateUrl || '';

            ctx.clearValidationState();
            ctx.clearReturnFlowFields();
            ctx.setModalMode({ mode: 'edit', updateUrl });
            ctx.fillFormValues(record, {
                usuarioPhotoUrl: button.dataset.fotoUsuarioUrl || '',
                bienPhotoUrl: button.dataset.fotoBienUrl || '',
            });
            ctx.modal.show();
        };

        ctx.initializeTooltips();

        document.getElementById(ctx.selectors.createButton)?.addEventListener('click', () => {
            ctx.openCreateModal();
        });

        document.querySelectorAll('.edit-row-btn').forEach((button) => {
            button.addEventListener('click', () => ctx.openEditModal(button));
        });

        [
            ['modal_responsable_display', 'modal_responsable', 'modal_responsable_options'],
            ['modal_cedula_usuario_display', 'modal_cedula_usuario', 'modal_cedula_usuario_options'],
            ['modal_cedulaResponsable_display', 'modal_cedulaResponsable', 'modal_cedula_responsable_options'],
        ].forEach(([displayId, hiddenId, datalistId]) => {
            const displayInput = document.getElementById(displayId);
            const hiddenInput = document.getElementById(hiddenId);
            if (!displayInput || !hiddenInput) {
                return;
            }

            displayInput.addEventListener('input', () => {
                ctx.normalizeReferenceInputToCedula(displayInput, hiddenInput, datalistId);
            });
            displayInput.addEventListener('change', () => {
                ctx.normalizeReferenceInputToCedula(displayInput, hiddenInput, datalistId);
            });
        });

        ctx.form.addEventListener('submit', () => {
            [
                ['modal_responsable_display', 'modal_responsable', 'modal_responsable_options'],
                ['modal_cedula_usuario_display', 'modal_cedula_usuario', 'modal_cedula_usuario_options'],
                ['modal_cedulaResponsable_display', 'modal_cedulaResponsable', 'modal_cedula_responsable_options'],
            ].forEach(([displayId, hiddenId, datalistId]) => {
                ctx.normalizeReferenceInputToCedula(
                    document.getElementById(displayId),
                    document.getElementById(hiddenId),
                    datalistId,
                );
            });
        });

        if (ctx.hasServerValidationErrors) {
            ctx.setReturnFlowFields({
                returnEntity: ctx.oldReturnEntity || '',
                returnUrl: ctx.oldReturnUrl || '',
                restoreDraftKey: ctx.oldRestoreDraftKey || '',
            });
            ctx.setModalMode({ mode: ctx.oldFormMode, updateUrl: ctx.oldUpdateUrl || '' });
            ctx.fillFormValues(ctx.oldValues || {});
            ctx.modal.show();
        }

        ctx.hooks.afterBoot.forEach((hook) => hook({ ctx }));
    };
</script><?php /**PATH C:\xampp\htdocs\almacen2\resources\views/administracion/crud/partials/comun/scripts/base.blade.php ENDPATH**/ ?>