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

    function parsePayload(btn) {
        const raw = btn.getAttribute('data-erp-actions');
        if (!raw) {
            return {
                entity: btn.getAttribute('data-item-type') || '',
                record: btn.getAttribute('data-item-id') || '',
                viewUrl: btn.getAttribute('data-view-href') || null,
                deleteUrl: btn.getAttribute('data-delete-url') || null,
            };
        }
        try {
            return JSON.parse(raw);
        } catch (e) {
            return {};
        }
    }

    function setVisible(el, visible) {
        if (!el) return;
        el.classList.toggle('d-none', !visible);
    }

    function submitForm(form, url, method) {
        if (!form || !url) return;
        form.action = url;
        const methodInput = form.querySelector('[data-role="method"]');
        if (methodInput) {
            methodInput.value = method || 'POST';
        }
        form.submit();
    }

    function openConfirm(modalRoot, confirmRoot, options) {
        if (!confirmRoot || !window.bootstrap) {
            if (window.confirm((options.title || '') + '\n\n' + (options.message || ''))) {
                options.onConfirm && options.onConfirm();
            }
            return;
        }

        const titleEl = confirmRoot.querySelector('[data-role="confirm-title"]');
        const messageEl = confirmRoot.querySelector('[data-role="confirm-message"]');
        const recordEl = confirmRoot.querySelector('[data-role="confirm-record"]');
        const hintEl = confirmRoot.querySelector('[data-role="confirm-hint"]');
        const submitEl = confirmRoot.querySelector('[data-role="confirm-submit"]');

        if (titleEl) titleEl.textContent = options.title || '';
        if (messageEl) messageEl.textContent = options.message || '';
        if (recordEl) {
            recordEl.textContent = options.record ? '"' + options.record + '"' : '';
            setVisible(recordEl, !!options.record);
        }
        if (hintEl) {
            hintEl.textContent = options.hint || '';
            setVisible(hintEl, !!options.hint);
        }
        if (submitEl) {
            submitEl.textContent = options.button || i18n.deleteButton || 'Delete';
            submitEl.classList.toggle('btn-danger', options.variant !== 'warning');
            submitEl.classList.toggle('btn-warning', options.variant === 'warning');
            submitEl.onclick = function () {
                const instance = bootstrap.Modal.getInstance(confirmRoot);
                if (instance) instance.hide();
                options.onConfirm && options.onConfirm();
            };
        }

        const actionsInstance = bootstrap.Modal.getInstance(modalRoot);
        if (actionsInstance) actionsInstance.hide();
        bootstrap.Modal.getOrCreateInstance(confirmRoot).show();
    }

    document.querySelectorAll('[data-erp-action-modal]').forEach(function (modalRoot) {
        const id = modalRoot.id;
        const confirmRoot = document.getElementById(id + 'Confirm');
        const form = document.getElementById(id + 'Form') || document.querySelector('[data-erp-action-form]');
        const subtitle = modalRoot.querySelector('[data-role="subtitle"]');
        const cards = {
            view: modalRoot.querySelector('[data-action="view"]'),
            edit: modalRoot.querySelector('[data-action="edit"]'),
            duplicate: modalRoot.querySelector('[data-action="duplicate"]'),
            print: modalRoot.querySelector('[data-action="print"]'),
            activate: modalRoot.querySelector('[data-action="activate"]'),
            deactivate: modalRoot.querySelector('[data-action="deactivate"]'),
            delete: modalRoot.querySelector('[data-action="delete"]'),
        };

        let current = {};

        document.querySelectorAll('[data-bs-target="#' + id + '"].js-open-actions').forEach(function (btn) {
            btn.addEventListener('click', function () {
                current = parsePayload(btn);

                if (subtitle) {
                    const parts = [current.entity, current.record].filter(Boolean);
                    subtitle.textContent = parts.length ? parts.join(' • ') : (i18n.selectedItem || '');
                }

                const bindLink = function (el, url) {
                    const ok = !!url;
                    setVisible(el, ok);
                    if (ok && el && el.tagName === 'A') {
                        el.setAttribute('href', url);
                    }
                };

                bindLink(cards.view, current.viewUrl);
                bindLink(cards.edit, current.editUrl);
                bindLink(cards.print, current.printUrl);

                setVisible(cards.duplicate, !!current.duplicateUrl);
                setVisible(cards.activate, !!current.activateUrl);
                setVisible(cards.deactivate, !!current.deactivateUrl);
                setVisible(cards.delete, !!current.deleteUrl);
            });
        });

        if (cards.duplicate) {
            cards.duplicate.addEventListener('click', function () {
                openConfirm(modalRoot, confirmRoot, {
                    title: (i18n.duplicateTitle || 'Duplicate :entity').replace(':entity', current.entity || ''),
                    message: i18n.duplicateMessage || 'Create a copy of this record?',
                    record: current.record || '',
                    button: i18n.duplicateButton || 'Duplicate',
                    variant: 'warning',
                    onConfirm: function () {
                        submitForm(form, current.duplicateUrl, 'POST');
                    },
                });
            });
        }

        if (cards.activate) {
            cards.activate.addEventListener('click', function () {
                openConfirm(modalRoot, confirmRoot, {
                    title: (i18n.activateTitle || 'Activate :entity').replace(':entity', current.entity || ''),
                    message: current.activateMessage || i18n.statusMessage || 'Are you sure you want to activate:',
                    record: current.record || '',
                    hint: current.activateHint || current.statusConfirmHint || '',
                    button: i18n.activateButton || 'Activate',
                    variant: 'warning',
                    onConfirm: function () {
                        submitForm(form, current.activateUrl, 'POST');
                    },
                });
            });
        }

        if (cards.deactivate) {
            cards.deactivate.addEventListener('click', function () {
                openConfirm(modalRoot, confirmRoot, {
                    title: (i18n.deactivateTitle || 'Deactivate :entity').replace(':entity', current.entity || ''),
                    message: current.deactivateMessage || i18n.statusMessage || 'Are you sure you want to deactivate:',
                    record: current.record || '',
                    hint: current.deactivateHint || current.statusConfirmHint || '',
                    button: i18n.deactivateButton || 'Deactivate',
                    variant: 'warning',
                    onConfirm: function () {
                        submitForm(form, current.deactivateUrl, 'POST');
                    },
                });
            });
        }

        if (cards.delete) {
            cards.delete.addEventListener('click', function () {
                openConfirm(modalRoot, confirmRoot, {
                    title: (i18n.deleteTitle || 'Delete :entity').replace(':entity', current.entity || ''),
                    message: current.deleteMessage || i18n.deleteMessage || 'Are you sure you want to delete:',
                    record: current.record || '',
                    hint: i18n.deleteIrreversible || 'This action cannot be undone.',
                    button: i18n.deleteButton || 'Delete',
                    variant: 'danger',
                    onConfirm: function () {
                        submitForm(form, current.deleteUrl, 'DELETE');
                    },
                });
            });
        }
    });
});
