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

        ctx.hooks.afterBoot.push(() => {
            const detailModalElement = document.getElementById(ctx.selectors.detailModal);
            const detailGrid = document.getElementById(ctx.selectors.detailGrid);
            const detailImageWrap = document.getElementById(ctx.selectors.detailImageWrap);
            const detailImage = document.getElementById(ctx.selectors.detailImage);
            if (!detailModalElement || !detailGrid) {
                return;
            }

            const detailModal = new bootstrap.Modal(detailModalElement);
            const formatDetailValue = (column, value) => {
                if (value === null || value === undefined || value === '') {
                    return 'No disponible';
                }
                const options = ctx.fieldOptions[column];
                if (options && Object.prototype.hasOwnProperty.call(options, value)) {
                    return options[value];
                }
                return value;
            };

            document.querySelectorAll('.detail-row-btn').forEach((button) => {
                button.addEventListener('click', () => {
                    const record = JSON.parse(button.dataset.detailRecord || '{}');
                    if (detailImageWrap && detailImage) {
                        detailImage.removeAttribute('src');
                        detailImageWrap.classList.add('d-none');
                    }

                    detailGrid.innerHTML = Object.entries(record)
                        .filter(([key]) => !['created_at', 'updated_at', 'deleted_at'].includes(key))
                        .map(([key, value]) => {
                            const label = typeof ctx.resolveFieldLabel === 'function'
                                ? ctx.resolveFieldLabel(key)
                                : key.replace(/_/g, ' ').replace(/\b\w/g, (letter) => letter.toUpperCase());
                            return `
                                <div class="detail-card">
                                    <div class="detail-label">${label}</div>
                                    <div class="detail-value">${formatDetailValue(key, value)}</div>
                                </div>
                            `;
                        })
                        .join('');

                    detailModal.show();
                });
            });
        });
    })();
</script>