function erpToast(text, variant) {
    let area = document.getElementById('erp-toast-area');
    if (!area) {
        area = document.createElement('div');
        area.id = 'erp-toast-area';
        area.className = 'erp-toast-area position-fixed bottom-0 end-0 p-3';
        area.style.zIndex = '1080';
        document.body.appendChild(area);
    }
    const el = document.createElement('div');
    el.className =
        'erp-toast alert shadow-sm small mb-2 ' +
        (variant === 'danger' ? 'alert-danger' : 'alert-success');
    el.setAttribute('role', 'status');
    el.textContent = text;
    area.appendChild(el);
    setTimeout(() => {
        el.classList.add('opacity-50');
        setTimeout(() => el.remove(), 4000);
    }, 6000);
}

function erpBulkSelectedCount(formId) {
    return document.querySelectorAll(
        `input[type="checkbox"][form="${formId}"]:checked`,
    ).length;
}

document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('[data-erp-select-page]').forEach((btn) => {
        btn.addEventListener('click', () => {
            const sel = btn.getAttribute('data-erp-select-page');
            const target = sel ? document.querySelector(sel) : null;
            const fid = target instanceof HTMLFormElement ? target.getAttribute('id') : null;
            if (!fid) return;
            document
                .querySelectorAll(`input[type="checkbox"][form="${fid}"]`)
                .forEach((c) => {
                    c.checked = true;
                });
        });
    });

    document.querySelectorAll('button[type="submit"][form][data-bulk-confirm]').forEach((btn) => {
        btn.addEventListener('click', (e) => {
            const fid = btn.getAttribute('form');
            if (!fid) return;
            const n = erpBulkSelectedCount(fid);
            if (n === 0) {
                e.preventDefault();
                const msg = window.__erpBulkMessages?.noneSelected ?? 'Select at least one row.';
                erpToast(msg, 'danger');
                return;
            }
            const tpl = btn.getAttribute('data-bulk-confirm') ?? '';
            const msg = tpl.replace('__COUNT__', String(n));
            if (!window.confirm(msg)) {
                e.preventDefault();
                return;
            }
            const val = btn.getAttribute('data-bulk-confirm-value');
            const form = document.getElementById(fid);
            if (form && val) {
                const h = form.querySelector('input[name="confirmation"]');
                if (h) h.value = val;
            }
        });
    });

    const br = document.getElementById('erp-bulk-result');
    if (br) {
        try {
            const data = JSON.parse(br.textContent);
            const ok = (data.succeeded || []).length;
            const fail = (data.failures || []).length;
            const label = data.label ?? '';
            const tpl =
                window.__erpBulkToastTemplate ??
                ':label — :ok ok, :fail failed.';
            const text = tpl
                .replace(':label', label)
                .replace(':ok', String(ok))
                .replace(':fail', String(fail));
            erpToast(text, fail > 0 ? 'danger' : 'success');
        } catch (_) {
            /* ignore */
        }
    }

    document.addEventListener('keydown', (e) => {
        if (e.key !== '?' || e.ctrlKey || e.metaKey || e.altKey) return;
        const tag = (e.target && e.target.tagName) || '';
        if (['INPUT', 'TEXTAREA', 'SELECT'].includes(String(tag))) return;
        e.preventDefault();
        const t = document.getElementById('erp-speed-hints');
        if (t) window.alert(t.textContent);
    });
});
