<script>
    (() => {
        const ctx = window.factoryCrud;
        if (!ctx) {
            return;
        }

        const originalOpenCreateModal = typeof ctx.openCreateModal === 'function'
            ? ctx.openCreateModal.bind(ctx)
            : null;

        const resolveSelectedBienId = () => {
            const createButton = document.getElementById('openCreateModalBtn');
            const buttonBienId = createButton?.dataset?.selectedBienId ?? '';

            if (buttonBienId !== '') {
                return buttonBienId;
            }

            return new URL(window.location.href).searchParams.get('bien_id') || '';
        };

        const resolveBienSelect = () => document.getElementById('modal_bien_id');

        const resolveBienMirrorInput = () => {
            let mirror = document.getElementById('modal_bien_id_locked');
            if (mirror) {
                return mirror;
            }

            const bienSelect = resolveBienSelect();
            if (!(bienSelect instanceof HTMLSelectElement) || !bienSelect.parentElement) {
                return null;
            }

            mirror = document.createElement('input');
            mirror.type = 'hidden';
            mirror.id = 'modal_bien_id_locked';
            mirror.name = 'bien_id';
            bienSelect.parentElement.appendChild(mirror);

            return mirror;
        };

        const syncBienFieldState = ({ selectedBienId = '', lock = false } = {}) => {
            const bienSelect = resolveBienSelect();
            if (!(bienSelect instanceof HTMLSelectElement)) {
                return;
            }

            const mirror = document.getElementById('modal_bien_id_locked');

            if (selectedBienId !== '') {
                bienSelect.value = selectedBienId;
            }

            if (!lock || selectedBienId === '') {
                bienSelect.disabled = false;
                bienSelect.removeAttribute('data-locked-by-history');
                if (mirror) {
                    mirror.remove();
                }
                return;
            }

            bienSelect.disabled = true;
            bienSelect.setAttribute('data-locked-by-history', 'true');

            const ensuredMirror = resolveBienMirrorInput();
            if (ensuredMirror) {
                ensuredMirror.value = selectedBienId;
            }
        };

        ctx.hooks.onSetModalMode.push(({ isEditMode }) => {
            if (isEditMode) {
                syncBienFieldState({ selectedBienId: '', lock: false });
            }
        });

        ctx.hooks.onFillFormValues.push(() => {
            const selectedBienId = resolveSelectedBienId();
            const isCreateMode = ctx.formModeInput?.value === 'create';

            syncBienFieldState({
                selectedBienId,
                lock: isCreateMode && selectedBienId !== '',
            });
        });

        if (originalOpenCreateModal) {
            ctx.openCreateModal = function openCreateModalWithSelectedBien() {
                originalOpenCreateModal();

                const selectedBienId = resolveSelectedBienId();
                if (selectedBienId === '') {
                    syncBienFieldState({ selectedBienId: '', lock: false });
                    return;
                }

                const currentValues = typeof ctx.collectCurrentFormValues === 'function'
                    ? ctx.collectCurrentFormValues()
                    : {};
                currentValues.bien_id = selectedBienId;
                ctx.fillFormValues(currentValues);
                syncBienFieldState({ selectedBienId, lock: true });
            };
        }

        ctx.hooks.afterBoot.push(() => {
            const params = new URL(window.location.href).searchParams;
            if (params.get('open_modal') !== 'create') {
                return;
            }

            const selectedBienId = params.get('selected_bien_id') || params.get('bien_id') || '';

            ctx.form.reset();
            ctx.clearValidationState();
            ctx.setModalMode({ mode: 'create' });
            ctx.setReturnFlowFields({
                returnEntity: params.get('return_entity') || '',
                returnUrl: params.get('return_url') || '',
                restoreDraftKey: params.get('restore_draft_key') || '',
            });

            const draft = ctx.readStoredDraft(params.get('restore_draft_key') || '') || {};
            if (selectedBienId !== '') {
                draft.bien_id = selectedBienId;
            }

            ctx.fillFormValues(draft);
            syncBienFieldState({ selectedBienId, lock: selectedBienId !== '' });
            ctx.cleanupFlowQueryParams('open_modal', 'selected_bien_id', 'return_entity', 'return_url', 'restore_draft_key');
            ctx.modal.show();
        });
    })();
</script>