/**
 * Modal Helper — Auto-load content from AJAX URL into modals
 */
const ModalHelper = {
    init() {
        document.addEventListener('click', (e) => {
            const trigger = e.target.closest('[data-ajax-url]');
            if (!trigger) return;

            const modalTarget = trigger.getAttribute('data-bs-target');
            if (!modalTarget) return;

            const modal = document.querySelector(modalTarget);
            if (!modal) return;

            const url = trigger.getAttribute('data-ajax-url');
            const bodyEl = modal.querySelector('.modal-body');

            if (bodyEl && url) {
                bodyEl.innerHTML = '<div class="text-center py-5"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div></div>';

                $.get(url)
                    .done(function(response) {
                        if (typeof response === 'object' && response.html) {
                            bodyEl.innerHTML = response.html;
                        } else if (typeof response === 'string') {
                            bodyEl.innerHTML = response;
                        } else {
                            bodyEl.innerHTML = '<pre>' + JSON.stringify(response, null, 2) + '</pre>';
                        }
                    })
                    .fail(function(xhr) {
                        bodyEl.innerHTML = '<div class="alert alert-danger">Failed to load content. Please try again.</div>';
                    });
            }
        });
    }
};

document.addEventListener('DOMContentLoaded', () => ModalHelper.init());