(function () {
    const root = document.documentElement;
    const savedTheme = localStorage.getItem('sos-tiketing-theme');
    if (savedTheme === 'dark' || savedTheme === 'light') {
        root.setAttribute('data-theme', savedTheme);
    }

    function setThemeIcon() {
        const btn = document.getElementById('themeToggle');
        if (!btn) return;
        const isDark = root.getAttribute('data-theme') === 'dark';
        btn.textContent = isDark ? '☀' : '☾';
        btn.title = isDark ? 'Prebaci na svetlu temu' : 'Prebaci na tamnu temu';
    }

    setThemeIcon();

    const themeToggle = document.getElementById('themeToggle');
    if (themeToggle) {
        themeToggle.addEventListener('click', function () {
            const next = root.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
            root.setAttribute('data-theme', next);
            localStorage.setItem('sos-tiketing-theme', next);
            setThemeIcon();
        });
    }


    const userMenuButton = document.getElementById('userMenuButton');
    const userDropdown = document.getElementById('userDropdown');

    function closeUserMenu() {
        if (!userMenuButton || !userDropdown) return;
        userDropdown.classList.remove('otvoren');
        userMenuButton.setAttribute('aria-expanded', 'false');
    }

    function toggleUserMenu() {
        if (!userMenuButton || !userDropdown) return;
        const isOpen = userDropdown.classList.contains('otvoren');
        userDropdown.classList.toggle('otvoren', !isOpen);
        userMenuButton.setAttribute('aria-expanded', isOpen ? 'false' : 'true');
        closeNotifMenu();
    }

    if (userMenuButton && userDropdown) {
        userMenuButton.addEventListener('click', function (event) {
            event.stopPropagation();
            toggleUserMenu();
        });
        userDropdown.addEventListener('click', function (event) {
            event.stopPropagation();
        });
        document.addEventListener('click', closeUserMenu);
        document.addEventListener('keydown', function (event) {
            if (event.key === 'Escape') closeUserMenu();
        });
    }



    const notifButton = document.getElementById('notifButton');
    const notifDropdown = document.getElementById('notifDropdown');

    function closeNotifMenu() {
        if (!notifButton || !notifDropdown) return;
        notifDropdown.classList.remove('otvoren');
        notifButton.setAttribute('aria-expanded', 'false');
    }

    function toggleNotifMenu() {
        if (!notifButton || !notifDropdown) return;
        const isOpen = notifDropdown.classList.contains('otvoren');
        notifDropdown.classList.toggle('otvoren', !isOpen);
        notifButton.setAttribute('aria-expanded', isOpen ? 'false' : 'true');
        closeUserMenu();
    }

    if (notifButton && notifDropdown) {
        notifButton.addEventListener('click', function (event) {
            event.stopPropagation();
            toggleNotifMenu();
        });
        notifDropdown.addEventListener('click', function (event) {
            event.stopPropagation();
        });
        document.addEventListener('click', closeNotifMenu);
        document.addEventListener('keydown', function (event) {
            if (event.key === 'Escape') closeNotifMenu();
        });
    }

    const menuButton = document.getElementById('mobileMenu');
    const sidebar = document.getElementById('primarySidebar');
    const overlay = document.getElementById('sidebarOverlay');

    function openSidebar() {
        if (!sidebar || !menuButton) return;
        sidebar.classList.add('otvoren');
        document.body.classList.add('scroll-blokiran');
        menuButton.setAttribute('aria-expanded', 'true');
        if (overlay) overlay.classList.add('aktivan');
    }

    function closeSidebar() {
        if (!sidebar || !menuButton) return;
        sidebar.classList.remove('otvoren');
        document.body.classList.remove('scroll-blokiran');
        menuButton.setAttribute('aria-expanded', 'false');
        if (overlay) overlay.classList.remove('aktivan');
    }

    if (menuButton && sidebar) {
        menuButton.addEventListener('click', function () {
            sidebar.classList.contains('otvoren') ? closeSidebar() : openSidebar();
        });
        if (overlay) overlay.addEventListener('click', closeSidebar);
        document.addEventListener('keydown', function (event) {
            if (event.key === 'Escape') closeSidebar();
        });
    }

    document.querySelectorAll('[data-toggle-password]').forEach(function (button) {
        button.addEventListener('click', function () {
            const target = document.getElementById(button.getAttribute('data-toggle-password'));
            if (!target) return;
            const showPassword = target.type === 'password';
            target.type = showPassword ? 'text' : 'password';
            button.classList.toggle('is-visible', showPassword);
            button.setAttribute('aria-label', showPassword ? 'Sakrij lozinku' : 'Prikaži lozinku');
            button.setAttribute('title', showPassword ? 'Sakrij lozinku' : 'Prikaži lozinku');
        });
    });

    document.querySelectorAll('[data-godina]').forEach(function (el) {
        el.textContent = new Date().getFullYear();
    });

    document.querySelectorAll('[data-auto-dismiss]').forEach(function (alert) {
        const delay = parseInt(alert.getAttribute('data-auto-dismiss'), 10) || 25000;
        window.setTimeout(function () {
            alert.classList.add('alert-hide');
            window.setTimeout(function () {
                if (alert.parentNode) alert.parentNode.removeChild(alert);
            }, 320);
        }, delay);
    });

    function fallbackCopy(text) {
        const temp = document.createElement('textarea');
        temp.value = text;
        temp.setAttribute('readonly', 'readonly');
        temp.style.position = 'fixed';
        temp.style.left = '-9999px';
        document.body.appendChild(temp);
        temp.select();
        try { document.execCommand('copy'); } catch (e) {}
        document.body.removeChild(temp);
    }

    document.querySelectorAll('[data-copy-value]').forEach(function (button) {
        button.addEventListener('click', function () {
            const value = button.getAttribute('data-copy-value') || '';
            if (!value) return;
            const original = button.textContent;
            const done = function () {
                button.textContent = 'Kopirano';
                button.classList.add('kopirano');
                window.setTimeout(function () {
                    button.textContent = original;
                    button.classList.remove('kopirano');
                }, 1800);
            };
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(value).then(done).catch(function () {
                    fallbackCopy(value);
                    done();
                });
            } else {
                fallbackCopy(value);
                done();
            }
        });
    });

    function initProfilePhotoCropper() {
        const input = document.getElementById('profilePhotoInput');
        const dropzone = document.getElementById('profilePhotoDropzone');
        const fileName = document.getElementById('profilePhotoFileName');
        const cropper = document.getElementById('profileCropper');
        const stage = document.getElementById('profileCropStage');
        const img = document.getElementById('profileCropImage');
        const zoom = document.getElementById('profileCropZoom');
        const hidden = document.getElementById('croppedPhotoData');
        const result = document.getElementById('profileCropResult');
        if (!input || !cropper || !stage || !img || !zoom || !hidden || !result) return;

        const state = {
            naturalWidth: 0,
            naturalHeight: 0,
            minScale: 1,
            zoom: 1,
            x: 0,
            y: 0,
            dragging: false,
            startX: 0,
            startY: 0,
            originX: 0,
            originY: 0,
            mime: 'image/jpeg'
        };
        let cropAnimationFrame = 0;
        let cropOutputTimer = 0;

        function maxFileSizeBytes() {
            return 2 * 1024 * 1024;
        }

        function formatFileSize(bytes) {
            if (!bytes) return '';
            const mb = bytes / (1024 * 1024);
            return mb >= 1 ? mb.toFixed(2) + ' MB' : Math.ceil(bytes / 1024) + ' KB';
        }

        function setFileName(file) {
            if (!fileName) return;
            fileName.textContent = file ? (file.name + ' · ' + formatFileSize(file.size)) : 'Nije izabrana fotografija';
        }

        function stageSize() {
            const rect = stage.getBoundingClientRect();
            const size = Math.max(220, Math.round(Math.min(rect.width || 320, rect.height || 320)));
            return { width: size, height: size };
        }

        function constrain() {
            const size = stageSize();
            const scale = state.minScale * state.zoom;
            const displayWidth = state.naturalWidth * scale;
            const displayHeight = state.naturalHeight * scale;

            if (displayWidth <= size.width) {
                state.x = (size.width - displayWidth) / 2;
            } else {
                state.x = Math.min(0, Math.max(size.width - displayWidth, state.x));
            }

            if (displayHeight <= size.height) {
                state.y = (size.height - displayHeight) / 2;
            } else {
                state.y = Math.min(0, Math.max(size.height - displayHeight, state.y));
            }
        }

        function updateCrop() {
            if (!state.naturalWidth || !state.naturalHeight) return;
            constrain();
            const size = stageSize();
            const scale = state.minScale * state.zoom;
            const displayWidth = state.naturalWidth * scale;
            const displayHeight = state.naturalHeight * scale;

            img.style.width = displayWidth + 'px';
            img.style.height = displayHeight + 'px';
            img.style.transform = 'translate(' + state.x + 'px, ' + state.y + 'px)';

            const canvas = document.createElement('canvas');
            canvas.width = 512;
            canvas.height = 512;
            const ctx = canvas.getContext('2d', { alpha: state.mime === 'image/png' });
            if (!ctx) return;
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            const sx = Math.max(0, -state.x / scale);
            const sy = Math.max(0, -state.y / scale);
            const sw = Math.min(state.naturalWidth - sx, size.width / scale);
            const sh = Math.min(state.naturalHeight - sy, size.height / scale);
            ctx.drawImage(img, sx, sy, sw, sh, 0, 0, canvas.width, canvas.height);

            const output = state.mime === 'image/png'
                ? canvas.toDataURL('image/png')
                : canvas.toDataURL('image/jpeg', 0.9);
            hidden.value = output;
            result.src = output;
        }

        function updateCropTransform() {
            if (!state.naturalWidth || !state.naturalHeight) return;
            constrain();
            const scale = state.minScale * state.zoom;
            img.style.width = state.naturalWidth * scale + 'px';
            img.style.height = state.naturalHeight * scale + 'px';
            img.style.transform = 'translate(' + state.x + 'px, ' + state.y + 'px)';
        }

        function scheduleCropUpdate() {
            if (!cropAnimationFrame) {
                cropAnimationFrame = window.requestAnimationFrame(function () {
                    cropAnimationFrame = 0;
                    updateCropTransform();
                });
            }
            window.clearTimeout(cropOutputTimer);
            cropOutputTimer = window.setTimeout(updateCrop, 120);
        }

        function flushCropUpdate() {
            if (cropAnimationFrame) {
                window.cancelAnimationFrame(cropAnimationFrame);
                cropAnimationFrame = 0;
            }
            window.clearTimeout(cropOutputTimer);
            cropOutputTimer = 0;
            updateCrop();
        }

        function resetCropper() {
            hidden.value = '';
            cropper.hidden = true;
            setFileName(null);
            if (dropzone) dropzone.classList.remove('has-file');
        }

        function assignFileToInput(file) {
            if (!file || !window.DataTransfer) return;
            try {
                const dataTransfer = new DataTransfer();
                dataTransfer.items.add(file);
                input.files = dataTransfer.files;
            } catch (e) {}
        }

        function loadFile(file) {
            hidden.value = '';
            if (!file) {
                resetCropper();
                return;
            }
            const allowed = ['image/jpeg', 'image/png'];
            if (!allowed.includes(file.type)) {
                input.value = '';
                resetCropper();
                window.alert('Dozvoljeni formati su JPG i PNG.');
                return;
            }
            if (file.size > maxFileSizeBytes()) {
                input.value = '';
                resetCropper();
                window.alert('Fotografija može imati maksimalno 2 MB.');
                return;
            }

            setFileName(file);
            if (dropzone) dropzone.classList.add('has-file');
            state.mime = file.type === 'image/png' ? 'image/png' : 'image/jpeg';
            const reader = new FileReader();
            reader.onload = function (event) {
                img.onload = function () {
                    state.naturalWidth = img.naturalWidth;
                    state.naturalHeight = img.naturalHeight;
                    const size = stageSize();
                    state.minScale = Math.max(size.width / state.naturalWidth, size.height / state.naturalHeight);
                    state.zoom = 1;
                    zoom.value = '1';
                    const scale = state.minScale * state.zoom;
                    state.x = (size.width - state.naturalWidth * scale) / 2;
                    state.y = (size.height - state.naturalHeight * scale) / 2;
                    cropper.hidden = false;
                    updateCrop();
                };
                img.src = String(event.target.result || '');
            };
            reader.readAsDataURL(file);
        }

        input.addEventListener('change', function () {
            loadFile(input.files && input.files[0] ? input.files[0] : null);
        });

        if (dropzone) {
            ['dragenter', 'dragover'].forEach(function (eventName) {
                dropzone.addEventListener(eventName, function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                    dropzone.classList.add('is-dragover');
                });
            });
            ['dragleave', 'drop'].forEach(function (eventName) {
                dropzone.addEventListener(eventName, function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                    dropzone.classList.remove('is-dragover');
                });
            });
            dropzone.addEventListener('drop', function (event) {
                const file = event.dataTransfer && event.dataTransfer.files && event.dataTransfer.files[0]
                    ? event.dataTransfer.files[0]
                    : null;
                if (!file) return;
                assignFileToInput(file);
                loadFile(file);
            });
        }

        zoom.addEventListener('input', function () {
            const previousZoom = state.zoom;
            const nextZoom = parseFloat(zoom.value) || 1;
            const size = stageSize();
            const centerX = size.width / 2;
            const centerY = size.height / 2;
            const previousScale = state.minScale * previousZoom;
            const nextScale = state.minScale * nextZoom;
            const imageCenterX = (centerX - state.x) / previousScale;
            const imageCenterY = (centerY - state.y) / previousScale;
            state.zoom = nextZoom;
            state.x = centerX - imageCenterX * nextScale;
            state.y = centerY - imageCenterY * nextScale;
            scheduleCropUpdate();
        });

        stage.addEventListener('pointerdown', function (event) {
            if (!state.naturalWidth || !state.naturalHeight) return;
            state.dragging = true;
            state.startX = event.clientX;
            state.startY = event.clientY;
            state.originX = state.x;
            state.originY = state.y;
            stage.setPointerCapture(event.pointerId);
            stage.classList.add('dragging');
        });

        stage.addEventListener('pointermove', function (event) {
            if (!state.dragging) return;
            state.x = state.originX + event.clientX - state.startX;
            state.y = state.originY + event.clientY - state.startY;
            scheduleCropUpdate();
        });

        function stopDrag(event) {
            if (!state.dragging) return;
            state.dragging = false;
            stage.classList.remove('dragging');
            try { stage.releasePointerCapture(event.pointerId); } catch (e) {}
            flushCropUpdate();
        }

        stage.addEventListener('pointerup', stopDrag);
        stage.addEventListener('pointercancel', stopDrag);
        window.addEventListener('resize', function () {
            if (!state.naturalWidth || !state.naturalHeight) return;
            const size = stageSize();
            state.minScale = Math.max(size.width / state.naturalWidth, size.height / state.naturalHeight);
            scheduleCropUpdate();
        });
        const photoForm = input.closest('form');
        if (photoForm) {
            photoForm.addEventListener('submit', function () {
                if (state.naturalWidth && state.naturalHeight) flushCropUpdate();
            });
        }
    }

    initProfilePhotoCropper();



    const attachmentInput = document.querySelector('[data-ticket-attachments]');
    const attachmentSelection = document.querySelector('[data-attachment-selection]');
    const attachmentDropzone = document.querySelector('[data-ticket-dropzone]');
    const attachmentFileList = document.querySelector('[data-ticket-file-list]');
    if (attachmentInput) {
        const maxFiles = Number(attachmentInput.getAttribute('data-max-files') || 10);
        const maxBytes = Number(attachmentInput.getAttribute('data-max-bytes') || 52428800);
        const allowedExtensions = ['jpg', 'jpeg', 'png', 'pdf', 'xls', 'xlsx', 'txt'];
        let selectedFiles = [];

        function syncAttachmentInput() {
            if (!window.DataTransfer) return;
            const transfer = new DataTransfer();
            selectedFiles.forEach(function (file) { transfer.items.add(file); });
            attachmentInput.files = transfer.files;
        }

        function updateAttachmentStatus() {
            const totalBytes = selectedFiles.reduce(function (total, file) { return total + file.size; }, 0);
            const totalMb = (totalBytes / 1024 / 1024).toFixed(1).replace('.', ',');
            const message = selectedFiles.length ? selectedFiles.length + ' fajl(ova), ukupno ' + totalMb + ' MB.' : '';
            attachmentInput.setCustomValidity('');
            if (attachmentSelection) attachmentSelection.textContent = message;
        }

        function renderAttachmentFiles() {
            if (!attachmentFileList) return;
            attachmentFileList.replaceChildren();
            const fragment = document.createDocumentFragment();
            selectedFiles.forEach(function (file, index) {
                const row = document.createElement('div');
                row.className = 'ticket-file-item';
                const info = document.createElement('div');
                const name = document.createElement('strong');
                name.textContent = file.name;
                const size = document.createElement('span');
                size.textContent = (file.size / 1024 / 1024).toFixed(2).replace('.', ',') + ' MB';
                info.append(name, size);
                const remove = document.createElement('button');
                remove.type = 'button';
                remove.className = 'ticket-file-remove';
                remove.textContent = 'Ukloni';
                remove.addEventListener('click', function () {
                    selectedFiles.splice(index, 1);
                    syncAttachmentInput();
                    renderAttachmentFiles();
                    updateAttachmentStatus();
                });
                row.append(info, remove);
                fragment.appendChild(row);
            });
            attachmentFileList.appendChild(fragment);
        }

        function addAttachmentFiles(fileList) {
            const incoming = Array.from(fileList || []);
            for (const file of incoming) {
                const extension = file.name.includes('.') ? file.name.split('.').pop().toLowerCase() : '';
                if (!allowedExtensions.includes(extension)) {
                    window.alert('Nedozvoljen format fajla: ' + file.name);
                    continue;
                }
                if (selectedFiles.length >= maxFiles) {
                    window.alert('Možete dodati najviše ' + maxFiles + ' fajlova.');
                    break;
                }
                const nextTotal = selectedFiles.reduce(function (total, item) { return total + item.size; }, 0) + file.size;
                if (nextTotal > maxBytes) {
                    window.alert('Ukupna veličina priloga ne sme biti veća od 50 MB.');
                    continue;
                }
                const duplicate = selectedFiles.some(function (item) {
                    return item.name === file.name && item.size === file.size && item.lastModified === file.lastModified;
                });
                if (!duplicate) selectedFiles.push(file);
            }
            syncAttachmentInput();
            renderAttachmentFiles();
            updateAttachmentStatus();
        }

        attachmentInput.addEventListener('change', function () { addAttachmentFiles(attachmentInput.files); });
        if (attachmentDropzone) {
            attachmentDropzone.addEventListener('click', function (event) {
                if (event.target !== attachmentInput) attachmentInput.click();
            });
            attachmentDropzone.addEventListener('keydown', function (event) {
                if (event.key === 'Enter' || event.key === ' ') {
                    event.preventDefault();
                    attachmentInput.click();
                }
            });
            ['dragenter', 'dragover'].forEach(function (eventName) {
                attachmentDropzone.addEventListener(eventName, function (event) {
                    event.preventDefault();
                    attachmentDropzone.classList.add('is-dragover');
                });
            });
            ['dragleave', 'drop'].forEach(function (eventName) {
                attachmentDropzone.addEventListener(eventName, function (event) {
                    event.preventDefault();
                    attachmentDropzone.classList.remove('is-dragover');
                });
            });
            attachmentDropzone.addEventListener('drop', function (event) {
                addAttachmentFiles(event.dataTransfer ? event.dataTransfer.files : []);
            });
        }
    }

    const descriptionInput = document.querySelector('[data-description-input]');
    const descriptionCounter = document.querySelector('[data-description-counter]');
    if (descriptionInput) {
        const missingDescriptionMessage = 'Molimo unesite opis problema.';
        const shortDescriptionMessage = 'Opis problema mora imati najmanje 10 karaktera.';
        const updateDescriptionCounter = function () {
            if (descriptionCounter) {
                descriptionCounter.textContent = descriptionInput.value.length + ' / ' + descriptionInput.maxLength;
            }
        };
        const clearDescriptionValidity = function () {
            descriptionInput.setCustomValidity('');
        };

        descriptionInput.addEventListener('invalid', function () {
            clearDescriptionValidity();
            if (descriptionInput.value.trim() === '') {
                descriptionInput.setCustomValidity(missingDescriptionMessage);
            } else if (descriptionInput.validity.tooShort) {
                descriptionInput.setCustomValidity(shortDescriptionMessage);
            }
        });

        descriptionInput.addEventListener('input', function () {
            clearDescriptionValidity();
            updateDescriptionCounter();
        });

        const descriptionForm = descriptionInput.closest('form');
        if (descriptionForm) {
            descriptionForm.addEventListener('submit', function (event) {
                clearDescriptionValidity();
                if (descriptionInput.value.trim() === '') {
                    event.preventDefault();
                    descriptionInput.setCustomValidity(missingDescriptionMessage);
                    descriptionInput.reportValidity();
                    descriptionInput.focus();
                }
            });
        }

        updateDescriptionCounter();
    }

    document.querySelectorAll('[data-confirm]').forEach(function (element) {
        if (element.tagName === 'FORM') {
            element.addEventListener('submit', function (event) {
                const message = element.getAttribute('data-confirm') || 'Da li ste sigurni?';
                if (!window.confirm(message)) {
                    event.preventDefault();
                    event.stopPropagation();
                }
            });
        } else {
            element.addEventListener('click', function (event) {
                const message = element.getAttribute('data-confirm') || 'Da li ste sigurni?';
                if (!window.confirm(message)) {
                    event.preventDefault();
                    event.stopPropagation();
                }
            });
        }
    });

    document.querySelectorAll('[data-equipment-create-trigger]').forEach(function (trigger) {
        trigger.addEventListener('click', function (event) {
            const createPanel = document.getElementById('dodaj-opremu');
            if (!createPanel) return;

            event.preventDefault();
            createPanel.open = true;
            window.requestAnimationFrame(function () {
                createPanel.scrollIntoView({
                    behavior: window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth',
                    block: 'start'
                });
            });
        });
    });

    document.querySelectorAll('[data-participant-picker]').forEach(function (picker) {
        const searchInput = picker.querySelector('[data-participant-search]');
        const resultsBox = picker.querySelector('[data-participant-results]');
        const selectedBox = picker.querySelector('[data-participant-selected]');
        const endpoint = picker.getAttribute('data-search-url') || 'participant_search.php';
        if (!searchInput || !resultsBox || !selectedBox) return;

        const selectedIds = new Set();
        let debounceTimer = null;
        let requestController = null;
        let activeIndex = -1;

        function bindRemoveButton(chip) {
            const id = String(chip.getAttribute('data-participant-id') || '');
            if (id) selectedIds.add(id);
            const removeButton = chip.querySelector('[data-remove-participant]');
            if (removeButton) {
                removeButton.addEventListener('click', function () {
                    if (id) selectedIds.delete(id);
                    chip.remove();
                    searchInput.focus();
                });
            }
        }

        selectedBox.querySelectorAll('[data-participant-id]').forEach(bindRemoveButton);

        function closeResults() {
            resultsBox.hidden = true;
            resultsBox.replaceChildren();
            searchInput.setAttribute('aria-expanded', 'false');
            activeIndex = -1;
        }

        function addParticipant(item) {
            const id = String(item.id || '');
            if (!id || selectedIds.has(id) || selectedIds.size >= 20) return;

            const chip = document.createElement('span');
            chip.className = 'participant-chip';
            chip.setAttribute('data-participant-id', id);

            const label = document.createElement('span');
            label.textContent = item.name + ' · ' + item.email;

            const remove = document.createElement('button');
            remove.type = 'button';
            remove.setAttribute('data-remove-participant', '');
            remove.setAttribute('aria-label', 'Ukloni učesnika ' + item.name);
            remove.textContent = '×';

            const hidden = document.createElement('input');
            hidden.type = 'hidden';
            hidden.name = 'participant_ids[]';
            hidden.value = id;

            chip.append(label, remove, hidden);
            selectedBox.appendChild(chip);
            bindRemoveButton(chip);
            searchInput.value = '';
            closeResults();
            searchInput.focus();
        }

        function setActiveResult(index) {
            const buttons = Array.from(resultsBox.querySelectorAll('button[data-participant-result]'));
            if (!buttons.length) return;
            activeIndex = (index + buttons.length) % buttons.length;
            buttons.forEach(function (button, buttonIndex) {
                button.classList.toggle('is-active', buttonIndex === activeIndex);
            });
            buttons[activeIndex].scrollIntoView({ block: 'nearest' });
        }

        function showResults(items) {
            resultsBox.replaceChildren();
            activeIndex = -1;
            const available = items.filter(function (item) {
                return !selectedIds.has(String(item.id));
            });

            if (!available.length) {
                const empty = document.createElement('div');
                empty.className = 'participant-result-empty';
                empty.textContent = 'Nema pronađenih korisnika.';
                resultsBox.appendChild(empty);
            } else {
                const fragment = document.createDocumentFragment();
                available.forEach(function (item) {
                    const button = document.createElement('button');
                    button.type = 'button';
                    button.setAttribute('role', 'option');
                    button.setAttribute('data-participant-result', '');
                    const name = document.createElement('strong');
                    name.textContent = item.name;
                    const email = document.createElement('span');
                    email.textContent = item.email;
                    button.append(name, email);
                    button.addEventListener('click', function () { addParticipant(item); });
                    fragment.appendChild(button);
                });
                resultsBox.appendChild(fragment);
            }
            resultsBox.hidden = false;
            searchInput.setAttribute('aria-expanded', 'true');
        }

        function searchParticipants() {
            const query = searchInput.value.trim();
            if (query.length < 2) {
                closeResults();
                return;
            }
            if (requestController) requestController.abort();
            requestController = new AbortController();
            const separator = endpoint.includes('?') ? '&' : '?';
            fetch(endpoint + separator + 'q=' + encodeURIComponent(query), {
                credentials: 'same-origin',
                headers: { 'Accept': 'application/json' },
                signal: requestController.signal
            })
                .then(function (response) {
                    if (!response.ok) throw new Error('Pretraga nije dostupna.');
                    return response.json();
                })
                .then(function (payload) {
                    if (searchInput.value.trim() === query) {
                        showResults(Array.isArray(payload.results) ? payload.results : []);
                    }
                })
                .catch(function (error) {
                    if (error.name !== 'AbortError' && searchInput.value.trim() === query) {
                        showResults([]);
                    }
                });
        }

        searchInput.addEventListener('input', function () {
            window.clearTimeout(debounceTimer);
            debounceTimer = window.setTimeout(searchParticipants, 250);
        });
        searchInput.addEventListener('keydown', function (event) {
            if (resultsBox.hidden) return;
            const buttons = resultsBox.querySelectorAll('button[data-participant-result]');
            if (event.key === 'ArrowDown' && buttons.length) {
                event.preventDefault();
                setActiveResult(activeIndex + 1);
            } else if (event.key === 'ArrowUp' && buttons.length) {
                event.preventDefault();
                setActiveResult(activeIndex - 1);
            } else if (event.key === 'Enter' && activeIndex >= 0 && buttons[activeIndex]) {
                event.preventDefault();
                buttons[activeIndex].click();
            } else if (event.key === 'Escape') {
                closeResults();
            }
        });
        document.addEventListener('click', function (event) {
            if (!picker.contains(event.target)) closeResults();
        });
    });

})();
