(function () {
    const $ = (sel, root = document) => root.querySelector(sel);

    const ipInput = $('#ip');
    const formIp = $('#reset-ip-form');
    const formAll = $('#reset-all-form');

    const btnConfirmIp = $('#btn-confirm-ip');
    const btnConfirmAll = $('#btn-confirm-all');
    const confirmIpVal = $('#confirm-ip-value');

    (function initMyIp() {
        const card = document.querySelector('.card[data-myip]');
        const my = card?.dataset.myip?.trim();
        const btn = $('#btn-myip');
        if (my && btn) {
            btn.disabled = false;
            btn.addEventListener('click', () => {
                ipInput.value = my;
                ipInput.dispatchEvent(new Event('input'));
                window.showToast?.({ text: `Użyto adresu: ${my}`, variant: 'dark' });
            });
        }
    })();

    // Walidacja IPv4 na żywo
    const ipv4 = /^\d{1,3}(\.\d{1,3}){3}$/;
    ipInput?.addEventListener('input', () => {
        const ok = ipv4.test(ipInput.value.trim());
        ipInput.classList.toggle('is-valid', ok);
        ipInput.classList.toggle('is-invalid', ipInput.value.length > 0 && !ok);
    });

    // Uzupełnij wartość w modalu przed submit
    document.getElementById('confirmResetIpModal')?.addEventListener('show.bs.modal', () => {
        const ip = ipInput.value.trim() || '—';
        confirmIpVal && (confirmIpVal.textContent = ip);
    });

    // Blokada przycisków na czas submitu + lekki feedback
    function withSubmitting(btn, fn) {
        if (!btn) return fn();
        const original = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Przetwarzanie...';
        const done = () => { btn.disabled = false; btn.innerHTML = original; };
        const ret = fn();
        // jeśli to klasyczny submit (nawigacja), UI i tak się przeładuje
        if (ret && ret.finally) ret.finally(done); else setTimeout(done, 1200);
    }

    // Submity (po potwierdzeniach w modalach)
    formIp?.addEventListener('submit', (e) => {
        if (!ipv4.test(ipInput.value.trim())) {
            e.preventDefault();
            ipInput.classList.add('is-invalid');
            window.showToast?.({ text: 'Nieprawidłowy adres IP.', variant: 'danger' });
            return;
        }
        withSubmitting(btnConfirmIp, () => null);
    });

    formAll?.addEventListener('submit', () => withSubmitting(btnConfirmAll, () => null));
})();
