/**
 * Niwa AI — Stock Managers dynamic form handler.
 *
 * Loaded only on the Admin Autonomy settings page.
 * Expects `niwaAdminStockManagers` to be localized via wp_localize_script with:
 *   - maxSm    {number} Maximum allowed stock managers
 *   - optKey   {string} WordPress option key for name attributes
 */
(function () {
    var cfg = window.niwaAdminStockManagers;
    if (!cfg) {
        return;
    }

    var maxSm  = parseInt(cfg.maxSm, 10) || 500;
    var optKey = cfg.optKey || '';

    function reindex() {
        var rows = document.querySelectorAll('#niwa-stock-managers-body .niwa-sm-row');
        rows.forEach(function (r, i) {
            var inputs = r.querySelectorAll('input');
            if (inputs[0]) {
                inputs[0].name = optKey + '[stock_managers][' + i + '][chat_id]';
            }
            if (inputs[1]) {
                inputs[1].name = optKey + '[stock_managers][' + i + '][label]';
            }
        });
    }

    var addBtn = document.getElementById('niwa-sm-add');
    if (addBtn) {
        addBtn.addEventListener('click', function () {
            var tbody = document.getElementById('niwa-stock-managers-body');
            if (tbody.querySelectorAll('.niwa-sm-row').length >= maxSm) {
                alert('Maksimalan broj stock managera je ' + maxSm + '.');
                return;
            }
            var tr = document.createElement('tr');
            tr.className = 'niwa-sm-row';
            tr.innerHTML = '<td><input type="text" name="" value="" class="regular-text" placeholder="npr. 123456789" /></td>' +
                '<td><input type="text" name="" value="" class="regular-text" placeholder="npr. Marko - magacioner" /></td>' +
                '<td><button type="button" class="button niwa-sm-remove" title="Ukloni">&times;</button></td>';
            tbody.appendChild(tr);
            reindex();
        });
    }

    document.addEventListener('click', function (e) {
        if (e.target.classList.contains('niwa-sm-remove')) {
            e.target.closest('.niwa-sm-row').remove();
            reindex();
        }
    });
})();
