(function () {
    const $ = (s, r = document) => r.querySelector(s);

    // --- helpers ---
    function toAbsoluteUrl(u) {
        try { return new URL(u, window.location.origin).href; } catch { return u; }
    }

    async function copyToClipboard(text) {
        try {
            if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
                await navigator.clipboard.writeText(text);
                return true;
            }
        } catch (_) { /* fallback below */ }

        // Fallback dla nieszyfrowanego HTTP / braku uprawnień
        const ta = document.createElement('textarea');
        ta.value = text;
        ta.setAttribute('readonly', '');
        ta.style.position = 'fixed';
        ta.style.top = '-1000px';
        ta.style.left = '-1000px';
        document.body.appendChild(ta);
        ta.select();
        ta.setSelectionRange(0, ta.value.length);
        let ok = false;
        try { ok = document.execCommand('copy'); } catch (_) { ok = false; }
        document.body.removeChild(ta);
        return ok;
    }

    function flashButton(btn, okText = 'Skopiowano!', ms = 1200) {
        if (!btn) return;
        const origText = btn.textContent;
        const hadSuccess = btn.classList.contains('btn-outline-success');
        btn.textContent = okText;
        btn.classList.add('btn-outline-success');
        btn.classList.remove('btn-outline-light', 'btn-outline-secondary');
        setTimeout(() => {
            btn.textContent = origText;
            btn.classList.toggle('btn-success', hadSuccess);
            if (btn.classList.contains('copy-url')) btn.classList.add('btn-outline-light');
            if (btn.classList.contains('copy-curl')) btn.classList.add('btn-outline-light');
        }, ms);
    }

    // --- main: endpoint buttons ---
    document.addEventListener('click', async (e) => {
        const btnUrl = e.target.closest('.copy-url');
        const btnCurl = e.target.closest('.copy-curl');

        if (btnUrl) {
            e.preventDefault();
            e.stopPropagation();
            const raw = btnUrl.dataset.url || '';
            const href = toAbsoluteUrl(raw);
            const ok = await copyToClipboard(href);
            if (ok) {
                flashButton(btnUrl);
                window.showToast?.({ text: 'Skopiowano URL.', variant: 'success' });
            } else {
                window.showToast?.({ text: 'Nie udało się skopiować URL.', variant: 'danger' });
            }
            return;
        }

        if (btnCurl) {
            e.preventDefault();
            e.stopPropagation();
            const raw = btnCurl.dataset.url || '';
            const href = toAbsoluteUrl(raw);
            const method = (btnCurl.dataset.method || 'GET').toUpperCase();
            const cmd = `curl -X ${method} "${href}" -H "Accept: application/json" -sS`;
            const ok = await copyToClipboard(cmd);
            if (ok) {
                flashButton(btnCurl);
                window.showToast?.({ text: 'Skopiowano cURL.', variant: 'success' });
            } else {
                window.showToast?.({ text: 'Nie udało się skopiować cURL.', variant: 'danger' });
            }
            return;
        }
    });

    // --- collapse label sync ---
    const epCollapseEl = $('#ep-collapse');
    const epToggleBtn = $('#btn-toggle-endpoints');
    if (epCollapseEl && epToggleBtn && window.bootstrap) {
        epCollapseEl.addEventListener('shown.bs.collapse', () => { epToggleBtn.textContent = 'Ukryj endpointy'; });
        epCollapseEl.addEventListener('hidden.bs.collapse', () => { epToggleBtn.textContent = 'Pokaż endpointy'; });
    }
})();
