document.addEventListener('DOMContentLoaded', function () {
    const i18n = window.erpActionsModalI18n || {};

    function deleteConfirmMessage(type, id) {
        const template = id
            ? (i18n.deleteConfirmWithId || 'Delete :type (#:id)?')
            : (i18n.deleteConfirm || 'Delete :type?');

        return template
            .replace(':type', type)
            .replace(':id', id || '');
    }

    document.querySelectorAll('.erp-actions-modal[id]').forEach(function (modal) {
        const id = modal.id;
        const subTitle = document.getElementById(id + 'SubTitle');
        const viewLink = document.getElementById(id + 'ViewLink');
        const deleteBtn = document.getElementById(id + 'DeleteBtn');

        if (!subTitle && !viewLink && !deleteBtn) {
            return;
        }

        let currentItem = { type: '', id: '', deleteUrl: '' };

        document.querySelectorAll('[data-bs-target="#' + id + '"].js-open-actions').forEach(function (btn) {
            btn.addEventListener('click', function () {
                currentItem = {
                    type: btn.getAttribute('data-item-type') || '',
                    id: btn.getAttribute('data-item-id') || '',
                    deleteUrl: btn.getAttribute('data-delete-url') || '',
                };
                const viewHref = btn.getAttribute('data-view-href') || '#';
                if (subTitle) {
                    subTitle.textContent = currentItem.type
                        + (currentItem.id ? ' • ' + currentItem.id : '');
                }
                if (viewLink) {
                    viewLink.setAttribute('href', viewHref);
                }
            });
        });

        if (deleteBtn) {
            deleteBtn.addEventListener('click', function () {
                if (!currentItem.deleteUrl) {
                    return;
                }
                const ok = window.confirm(
                    deleteConfirmMessage(currentItem.type, currentItem.id)
                );
                if (!ok) {
                    return;
                }

                const token = document.querySelector('meta[name="csrf-token"]')?.content || '';
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = currentItem.deleteUrl;
                form.innerHTML =
                    '<input type="hidden" name="_token" value="' + token + '">' +
                    '<input type="hidden" name="_method" value="DELETE">';
                document.body.appendChild(form);
                form.submit();
            });
        }
    });
});
